text:
/**
 * \file
 *         Code for tunnelling uIP packets over the Rime mesh routing module
 *
 * \author  Adam Dunkels <adam@sics.se>\author
 * \author  Mathilde Durvy <mdurvy@cisco.com> (IPv6 related code)
 * \author  Julien Abeille <jabeille@cisco.com> (IPv6 related code)
 */

#include "contiki-net.h"
#include "net/ip/uip-split.h"
#include "net/ip/uip-packetqueue.h"

#if NETSTACK_CONF_WITH_IPV6
#include "net/ipv6/uip-nd6.h"
#include "net/ipv6/uip-ds6.h"
#endif

#include <string.h>

#define DEBUG DEBUG_NONE
#include "net/ip/uip-debug.h"

#if UIP_LOGGING
#include <stdio.h>
void uip_log(char *msg);
#define UIP_LOG(m) uip_log(m)
#else
#define UIP_LOG(m)
#endif

#define UIP_ICMP_BUF ((struct uip_icmp_hdr *)&uip_buf[UIP_LLIPH_LEN + uip_ext_len])
#define UIP_IP_BUF ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN])
#define UIP_TCP_BUF ((struct uip_tcpip_hdr *)&uip_buf[UIP_LLH_LEN])

#ifdef UIP_FALLBACK_INTERFACE
extern struct uip_fallback_interface UIP_FALLBACK_INTERFACE;
#endif

#if UIP_CONF_IPV6_RPL
#include "rpl/rpl.h"
#endif

process_event_t tcpip_event;
#if UIP_CONF_ICMP6
process_event_t tcpip_icmp6_event;
#endif /* UIP_CONF_ICMP6 */

/* Periodic check of active connections. */
static struct etimer periodic;

#if NETSTACK_CONF_WITH_IPV6 && UIP_CONF_IPV6_REASSEMBLY
/* Timer for reassembly. */
extern struct etimer uip_reass_timer;
#endif

#if UIP_TCP
/**
 * \internal Structure for holding a TCP port and a process ID.
 */
struct listenport {
  uint16_t port;
  struct process *p;
};

static struct internal_state {
  struct listenport listenports[UIP_LISTENPORTS];
  struct process *p;
} s;
#endif

enum {
  TCP_POLL,
  UDP_POLL,
  PACKET_INPUT
};

/* Called on IP packet output. */
#if NETSTACK_CONF_WITH_IPV6

static uint8_t (* outputfunc)(const uip_lladdr_t *a);

uint8_t
tcpip_output(const uip_lladdr_t *a)
{
  int ret;
  if(outputfunc != NULL) {
    ret = outputfunc(a);
    return ret;
  }
  UIP_LOG("tcpip_output: Use tcpip_set_outputfunc() to set an output function");
  return 0;
}

void
tcpip_set_outputfunc(uint8_t (*f)(const uip_lladdr_t *))
{
  outputfunc = f;
}
#else

static uint8_t (* outputfunc)(void);
uint8_t
tcpip_output(void)
{
  if(outputfunc != NULL) {
    return outputfunc();
  }
  UIP_LOG("tcpip_output: Use tcpip_set_outputfunc() to set an output function");
  return 0;
}

void
tcpip_set_outputfunc(uint8_t (*f)(void))
{
  outputfunc = f;
}
#endif

#if UIP_CONF_IP_FORWARD
unsigned char tcpip_is_forwarding; /* Forwarding right now? */
#endif /* UIP_CONF_IP_FORWARD */

PROCESS(tcpip_process, "TCP/IP stack");

/*---------------------------------------------------------------------------*/
#if UIP_TCP || UIP_CONF_IP_FORWARD
static void
start_periodic_tcp_timer(void)
{
  if(etimer_expired(&periodic)) {
    etimer_restart(&periodic);
  }
}
#endif /* UIP_TCP || UIP_CONF_IP_FORWARD */
/*---------------------------------------------------------------------------*/
static void
check_for_tcp_syn(void)
{
#if UIP_TCP || UIP_CONF_IP_FORWARD
  /* This is a hack that is needed to start the periodic TCP timer if
     an incoming packet contains a SYN: since uIP does not inform the
     application if a SYN arrives, we have no other way of starting
     this timer.  This function is called for every incoming IP packet
     to check for such SYNs. */
#define TCP_SYN 0x02
  if(UIP_IP_BUF->proto == UIP_PROTO_TCP &&
     (UIP_TCP_BUF->flags & TCP_SYN) == TCP_SYN) {
    start_periodic_tcp_timer();
  }
#endif /* UIP_TCP || UIP_CONF_IP_FORWARD */
}
/*---------------------------------------------------------------------------*/
static void
packet_input(void)
{
  if(uip_len > 0) {

#if UIP_CONF_IP_FORWARD
    tcpip_is_forwarding = 1;
    if(uip_fw_forward() != UIP_FW_LOCAL) {
      tcpip_is_forwarding = 0;
      return;
    }
    tcpip_is_forwarding = 0;
#endif /* UIP_CONF_IP_FORWARD */

    check_for_tcp_syn();
    uip_input();
    if(uip_len > 0) {
#if UIP_CONF_TCP_SPLIT
      uip_split_output();
#else /* UIP_CONF_TCP_SPLIT */
#if NETSTACK_CONF_WITH_IPV6
      tcpip_ipv6_output();
#else /* NETSTACK_CONF_WITH_IPV6 */
      PRINTF("tcpip packet_input output len %d\n", uip_len);
      tcpip_output();
#endif /* NETSTACK_CONF_WITH_IPV6 */
#endif /* UIP_CONF_TCP_SPLIT */
    }
  }
}
/*---------------------------------------------------------------------------*/
#if UIP_TCP
#if UIP_ACTIVE_OPEN
struct uip_conn *
tcp_connect(const uip_ipaddr_t *ripaddr, uint16_t port, void *appstate)
{
  struct uip_conn *c;

  c = uip_connect(ripaddr, port);
  if(c == NULL) {
    return NULL;
  }

  c->appstate.p = PROCESS_CURRENT();
  c->appstate.state = appstate;

  tcpip_poll_tcp(c);

  return c;
}
#endif /* UIP_ACTIVE_OPEN */
/*---------------------------------------------------------------------------*/
void
tcp_unlisten(uint16_t port)
{
  static unsigned char i;
  struct listenport *l;

  l = s.listenports;
  for(i = 0; i < UIP_LISTENPORTS; ++i) {
    if(l->port == port &&
       l->p == PROCESS_CURRENT()) {
      l->port = 0;
      uip_unlisten(port);
      break;
    }
    ++l;
  }
}
/*---------------------------------------------------------------------------*/
void
tcp_listen(uint16_t port)
{
  static unsigned char i;
  struct listenport *l;

  l = s.listenports;
  for(i = 0; i < UIP_LISTENPORTS; ++i) {
    if(l->port == 0) {
      l->port = port;
      l->p = PROCESS_CURRENT();
      uip_listen(port);
      break;
    }
    ++l;
  }
}
/*---------------------------------------------------------------------------*/
void
tcp_attach(struct uip_conn *conn,
	   void *appstate)
{
  uip_tcp_appstate_t *s;

  s = &conn->appstate;
  s->p = PROCESS_CURRENT();
  s->state = appstate;
}

#endif /* UIP_TCP */
/*---------------------------------------------------------------------------*/
#if UIP_UDP
void
udp_attach(struct uip_udp_conn *conn,
	   void *appstate)
{
  uip_udp_appstate_t *s;

  s = &conn->appstate;
  s->p = PROCESS_CURRENT();
  s->state = appstate;
}
/*---------------------------------------------------------------------------*/
struct uip_udp_conn *
udp_new(const uip_ipaddr_t *ripaddr, uint16_t port, void *appstate)
{
  struct uip_udp_conn *c;
  uip_udp_appstate_t *s;

  c = uip_udp_new(ripaddr, port);
  if(c == NULL) {
    return NULL;
  }

  s = &c->appstate;
  s->p = PROCESS_CURRENT();
  s->state = appstate;

  return c;
}
/*---------------------------------------------------------------------------*/
struct uip_udp_conn *
udp_broadcast_new(uint16_t port, void *appstate)
{
  uip_ipaddr_t addr;
  struct uip_udp_conn *conn;

#if NETSTACK_CONF_WITH_IPV6
  uip_create_linklocal_allnodes_mcast(&addr);
#else
  uip_ipaddr(&addr, 255,255,255,255);
#endif /* NETSTACK_CONF_WITH_IPV6 */
  conn = udp_new(&addr, port, appstate);
  if(conn != NULL) {
    udp_bind(conn, port);
  }
  return conn;
}
#endif /* UIP_UDP */
/*---------------------------------------------------------------------------*/
#if UIP_CONF_ICMP6
uint8_t
icmp6_new(void *appstate) {
  if(uip_icmp6_conns.appstate.p == PROCESS_NONE) {
    uip_icmp6_conns.appstate.p = PROCESS_CURRENT();
    uip_icmp6_conns.appstate.state = appstate;
    return 0;
  }
  return 1;
}

void
tcpip_icmp6_call(uint8_t type)
{
  if(uip_icmp6_conns.appstate.p != PROCESS_NONE) {
    /* XXX: This is a hack that needs to be updated. Passing a pointer (&type)
       like this only works with process_post_synch. */
    process_post_synch(uip_icmp6_conns.appstate.p, tcpip_icmp6_event, &type);
  }
  return;
}
#endif /* UIP_CONF_ICMP6 */
/*---------------------------------------------------------------------------*/
static void
eventhandler(process_event_t ev, process_data_t data)
{
#if UIP_TCP
  static unsigned char i;
  register struct listenport *l;
#endif /*UIP_TCP*/
  struct process *p;

  switch(ev) {
    case PROCESS_EVENT_EXITED:
      /* This is the event we get if a process has exited. We go through
         the TCP/IP tables to see if this process had any open
         connections or listening TCP ports. If so, we'll close those
         connections. */

      p = (struct process *)data;
#if UIP_TCP
      l = s.listenports;
      for(i = 0; i < UIP_LISTENPORTS; ++i) {
        if(l->p == p) {
          uip_unlisten(l->port);
          l->port = 0;
          l->p = PROCESS_NONE;
        }
        ++l;
      }

      {
        struct uip_conn *cptr;

        for(cptr = &uip_conns[0]; cptr < &uip_conns[UIP_CONNS]; ++cptr) {
          if(cptr->appstate.p == p) {
            cptr->appstate.p = PROCESS_NONE;
            cptr->tcpstateflags = UIP_CLOSED;
          }
        }
      }
#endif /* UIP_TCP */
#if UIP_UDP
      {
        struct uip_udp_conn *cptr;

        for(cptr = &uip_udp_conns[0];
            cptr < &uip_udp_conns[UIP_UDP_CONNS]; ++cptr) {
          if(cptr->appstate.p == p) {
            cptr->lport = 0;
          }
        }
      }
#endif /* UIP_UDP */
      break;

    case PROCESS_EVENT_TIMER:
      /* We get this event if one of our timers have expired. */
      {
        /* Check the clock so see if we should call the periodic uIP
           processing. */
        if(data == &periodic &&
           etimer_expired(&periodic)) {
#if UIP_TCP
          for(i = 0; i < UIP_CONNS; ++i) {
            if(uip_conn_active(i)) {
              /* Only restart the timer if there are active
                 connections. */
              etimer_restart(&periodic);
              uip_periodic(i);
#if NETSTACK_CONF_WITH_IPV6
              tcpip_ipv6_output();
#else
              if(uip_len > 0) {
		PRINTF("tcpip_output from periodic len %d\n", uip_len);
                tcpip_output();
		PRINTF("tcpip_output after periodic len %d\n", uip_len);
              }
#endif /* NETSTACK_CONF_WITH_IPV6 */
            }
          }
#endif /* UIP_TCP */
#if UIP_CONF_IP_FORWARD
          uip_fw_periodic();
#endif /* UIP_CONF_IP_FORWARD */
        }

#if NETSTACK_CONF_WITH_IPV6
#if UIP_CONF_IPV6_REASSEMBLY
        /*
         * check the timer for reassembly
         */
        if(data == &uip_reass_timer &&
           etimer_expired(&uip_reass_timer)) {
          uip_reass_over();
          tcpip_ipv6_output();
        }
#endif /* UIP_CONF_IPV6_REASSEMBLY */
        /*
         * check the different timers for neighbor discovery and
         * stateless autoconfiguration
         */
        /*if(data == &uip_ds6_timer_periodic &&
           etimer_expired(&uip_ds6_timer_periodic)) {
          uip_ds6_periodic();
          tcpip_ipv6_output();
        }*/
#if !UIP_CONF_ROUTER
        if(data == &uip_ds6_timer_rs &&
           etimer_expired(&uip_ds6_timer_rs)) {
          uip_ds6_send_rs();
          tcpip_ipv6_output();
        }
#endif /* !UIP_CONF_ROUTER */
        if(data == &uip_ds6_timer_periodic &&
           etimer_expired(&uip_ds6_timer_periodic)) {
          uip_ds6_periodic();
          tcpip_ipv6_output();
        }
#endif /* NETSTACK_CONF_WITH_IPV6 */
      }
      break;

#if UIP_TCP
    case TCP_POLL:
      if(data != NULL) {
        uip_poll_conn(data);
#if NETSTACK_CONF_WITH_IPV6
        tcpip_ipv6_output();
#else /* NETSTACK_CONF_WITH_IPV6 */
        if(uip_len > 0) {
	  PRINTF("tcpip_output from tcp poll len %d\n", uip_len);
          tcpip_output();
        }
#endif /* NETSTACK_CONF_WITH_IPV6 */
        /* Start the periodic polling, if it isn't already active. */
        start_periodic_tcp_timer();
      }
      break;
#endif /* UIP_TCP */
#if UIP_UDP
    case UDP_POLL:
      if(data != NULL) {
        uip_udp_periodic_conn(data);
#if NETSTACK_CONF_WITH_IPV6
        tcpip_ipv6_output();
#else
        if(uip_len > 0) {
          tcpip_output();
        }
#endif /* UIP_UDP */
      }
      break;
#endif /* UIP_UDP */

    case PACKET_INPUT:
      packet_input();
      break;
  };
}
/*---------------------------------------------------------------------------*/
void
tcpip_input(void)
{
  process_post_synch(&tcpip_process, PACKET_INPUT, NULL);
  uip_clear_buf();
}
/*---------------------------------------------------------------------------*/
#if NETSTACK_CONF_WITH_IPV6
void
tcpip_ipv6_output(void)
{
  uip_ds6_nbr_t *nbr = NULL;
  uip_ipaddr_t *nexthop;

  if(uip_len == 0) {
    return;
  }

  if(uip_len > UIP_LINK_MTU) {
    UIP_LOG("tcpip_ipv6_output: Packet to big");
    uip_clear_buf();
    return;
  }

  if(uip_is_addr_unspecified(&UIP_IP_BUF->destipaddr)){
    UIP_LOG("tcpip_ipv6_output: Destination address unspecified");
    uip_clear_buf();
    return;
  }

  if(!uip_is_addr_mcast(&UIP_IP_BUF->destipaddr)) {
    /* Next hop determination */
    nbr = NULL;

    /* We first check if the destination address is on our immediate
       link. If so, we simply use the destination address as our
       nexthop address. */
    if(uip_ds6_is_addr_onlink(&UIP_IP_BUF->destipaddr)){
      nexthop = &UIP_IP_BUF->destipaddr;
    } else {
      uip_ds6_route_t *route;
      /* Check if we have a route to the destination address. */
      route = uip_ds6_route_lookup(&UIP_IP_BUF->destipaddr);

      /* No route was found - we send to the default route instead. */
      if(route == NULL) {
        PRINTF("tcpip_ipv6_output: no route found, using default route\n");
        nexthop = uip_ds6_defrt_choose();
        if(nexthop == NULL) {
#ifdef UIP_FALLBACK_INTERFACE
	  PRINTF("FALLBACK: removing ext hdrs & setting proto %d %d\n",
		 uip_ext_len, *((uint8_t *)UIP_IP_BUF + 40));
	  if(uip_ext_len > 0) {
	    extern void remove_ext_hdr(void);
	    uint8_t proto = *((uint8_t *)UIP_IP_BUF + 40);
	    remove_ext_hdr();
	    /* This should be copied from the ext header... */
	    UIP_IP_BUF->proto = proto;
	  }
	  /* Inform the other end that the destination is not reachable. If it's
	   * not informed routes might get lost unexpectedly until there's a need
	   * to send a new packet to the peer */
	  if(UIP_FALLBACK_INTERFACE.output() < 0) {
	    PRINTF("FALLBACK: output error. Reporting DST UNREACH\n");
	    uip_icmp6_error_output(ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR, 0);
	    uip_flags = 0;
	    tcpip_ipv6_output();
	    return;
	  }
#else
          PRINTF("tcpip_ipv6_output: Destination off-link but no route\n");
#endif /* !UIP_FALLBACK_INTERFACE */
          uip_clear_buf();
          return;
        }

      } else {
        /* A route was found, so we look up the nexthop neighbor for
           the route. */
        nexthop = uip_ds6_route_nexthop(route);

        /* If the nexthop is dead, for example because the neighbor
           never responded to link-layer acks, we drop its route. */
        if(nexthop == NULL) {
#if UIP_CONF_IPV6_RPL
          /* If we are running RPL, and if we are the root of the
             network, we'll trigger a global repair berfore we remove
             the route. */
          rpl_dag_t *dag;
          rpl_instance_t *instance;

          dag = (rpl_dag_t *)route->state.dag;
          if(dag != NULL) {
            instance = dag->instance;

            rpl_repair_root(instance->instance_id);
          }
#endif /* UIP_CONF_IPV6_RPL */
          uip_ds6_route_rm(route);

          /* We don't have a nexthop to send the packet to, so we drop
             it. */
          return;
        }
      }
#if TCPIP_CONF_ANNOTATE_TRANSMISSIONS
      if(nexthop != NULL) {
        static uint8_t annotate_last;
        static uint8_t annotate_has_last = 0;

        if(annotate_has_last) {
          printf("#L %u 0; red\n", annotate_last);
        }
        printf("#L %u 1; red\n", nexthop->u8[sizeof(uip_ipaddr_t) - 1]);
        annotate_last = nexthop->u8[sizeof(uip_ipaddr_t) - 1];
        annotate_has_last = 1;
      }
#endif /* TCPIP_CONF_ANNOTATE_TRANSMISSIONS */
    }

    /* End of next hop determination */

#if UIP_CONF_IPV6_RPL
    if(rpl_update_header_final(nexthop)) {
      uip_clear_buf();
      return;
    }
#endif /* UIP_CONF_IPV6_RPL */
    nbr = uip_ds6_nbr_lookup(nexthop);
    if(nbr == NULL) {
#if UIP_ND6_SEND_NA
      if((nbr = uip_ds6_nbr_add(nexthop, NULL, 0, NBR_INCOMPLETE)) == NULL) {
        uip_clear_buf();
        return;
      } else {
#if UIP_CONF_IPV6_QUEUE_PKT
        /* Copy outgoing pkt in the queuing buffer for later transmit. */
        if(uip_packetqueue_alloc(&nbr->packethandle, UIP_DS6_NBR_PACKET_LIFETIME) != NULL) {
          memcpy(uip_packetqueue_buf(&nbr->packethandle), UIP_IP_BUF, uip_len);
          uip_packetqueue_set_buflen(&nbr->packethandle, uip_len);
        }
#endif
      /* RFC4861, 7.2.2:
       * "If the source address of the packet prompting the solicitation is the
       * same as one of the addresses assigned to the outgoing interface, that
       * address SHOULD be placed in the IP Source Address of the outgoing
       * solicitation.  Otherwise, any one of the addresses assigned to the
       * interface should be used."*/
       if(uip_ds6_is_my_addr(&UIP_IP_BUF->srcipaddr)){
          uip_nd6_ns_output(&UIP_IP_BUF->srcipaddr, NULL, &nbr->ipaddr);
        } else {
          uip_nd6_ns_output(NULL, NULL, &nbr->ipaddr);
        }

        stimer_set(&nbr->sendns, uip_ds6_if.retrans_timer / 1000);
        nbr->nscount = 1;
        /* Send the first NS try from here (multicast destination IP address). */
      }
#else /* UIP_ND6_SEND_NA */
      uip_len = 0;
      return;
#endif /* UIP_ND6_SEND_NA */
    } else {
#if UIP_ND6_SEND_NA
      if(nbr->state == NBR_INCOMPLETE) {
        PRINTF("tcpip_ipv6_output: nbr cache entry incomplete\n");
#if UIP_CONF_IPV6_QUEUE_PKT
        /* Copy outgoing pkt in the queuing buffer for later transmit and set
           the destination nbr to nbr. */
        if(uip_packetqueue_alloc(&nbr->packethandle, UIP_DS6_NBR_PACKET_LIFETIME) != NULL) {
          memcpy(uip_packetqueue_buf(&nbr->packethandle), UIP_IP_BUF, uip_len);
          uip_packetqueue_set_buflen(&nbr->packethandle, uip_len);
        }
#endif /*UIP_CONF_IPV6_QUEUE_PKT*/
        uip_clear_buf();
        return;
      }
      /* Send in parallel if we are running NUD (nbc state is either STALE,
         DELAY, or PROBE). See RFC 4861, section 7.3.3 on node behavior. */
      if(nbr->state == NBR_STALE) {
        nbr->state = NBR_DELAY;
        stimer_set(&nbr->reachable, UIP_ND6_DELAY_FIRST_PROBE_TIME);
        nbr->nscount = 0;
        PRINTF("tcpip_ipv6_output: nbr cache entry stale moving to delay\n");
      }
#endif /* UIP_ND6_SEND_NA */

      tcpip_output(uip_ds6_nbr_get_ll(nbr));

#if UIP_CONF_IPV6_QUEUE_PKT
      /*
       * Send the queued packets from here, may not be 100% perfect though.
       * This happens in a few cases, for example when instead of receiving a
       * NA after sendiong a NS, you receive a NS with SLLAO: the entry moves
       * to STALE, and you must both send a NA and the queued packet.
       */
      if(uip_packetqueue_buflen(&nbr->packethandle) != 0) {
        uip_len = uip_packetqueue_buflen(&nbr->packethandle);
        memcpy(UIP_IP_BUF, uip_packetqueue_buf(&nbr->packethandle), uip_len);
        uip_packetqueue_free(&nbr->packethandle);
        tcpip_output(uip_ds6_nbr_get_ll(nbr));
      }
#endif /*UIP_CONF_IPV6_QUEUE_PKT*/

      uip_clear_buf();
      return;
    }
  }
  /* Multicast IP destination address. */
  tcpip_output(NULL);
  uip_clear_buf();
}
#endif /* NETSTACK_CONF_WITH_IPV6 */
/*---------------------------------------------------------------------------*/
#if UIP_UDP
void
tcpip_poll_udp(struct uip_udp_conn *conn)
{
  process_post(&tcpip_process, UDP_POLL, conn);
}
#endif /* UIP_UDP */
/*---------------------------------------------------------------------------*/
#if UIP_TCP
void
tcpip_poll_tcp(struct uip_conn *conn)
{
  process_post(&tcpip_process, TCP_POLL, conn);
}
#endif /* UIP_TCP */
/*---------------------------------------------------------------------------*/
void
tcpip_uipcall(void)
{
  uip_udp_appstate_t *ts;

#if UIP_UDP
  if(uip_conn != NULL) {
    ts = &uip_conn->appstate;
  } else {
    ts = &uip_udp_conn->appstate;
  }
#else /* UIP_UDP */
  ts = &uip_conn->appstate;
#endif /* UIP_UDP */

#if UIP_TCP
 {
   static unsigned char i;
   struct listenport *l;

   /* If this is a connection request for a listening port, we must
      mark the connection with the right process ID. */
   if(uip_connected()) {
     l = &s.listenports[0];
     for(i = 0; i < UIP_LISTENPORTS; ++i) {
       if(l->port == uip_conn->lport &&
	  l->p != PROCESS_NONE) {
	 ts->p = l->p;
	 ts->state = NULL;
	 break;
       }
       ++l;
     }

     /* Start the periodic polling, if it isn't already active. */
     start_periodic_tcp_timer();
   }
 }
#endif /* UIP_TCP */

  if(ts->p != NULL) {
    process_post_synch(ts->p, tcpip_event, ts->state);
  }
}
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(tcpip_process, ev, data)
{
  PROCESS_BEGIN();

#if UIP_TCP
 {
   static unsigned char i;

   for(i = 0; i < UIP_LISTENPORTS; ++i) {
     s.listenports[i].port = 0;
   }
   s.p = PROCESS_CURRENT();
 }
#endif

  tcpip_event = process_alloc_event();
#if UIP_CONF_ICMP6
  tcpip_icmp6_event = process_alloc_event();
#endif /* UIP_CONF_ICMP6 */
  etimer_set(&periodic, CLOCK_SECOND / 2);

  uip_init();
#ifdef UIP_FALLBACK_INTERFACE
  UIP_FALLBACK_INTERFACE.init();
#endif
/* initialize RPL if configured for using RPL */
#if NETSTACK_CONF_WITH_IPV6 && UIP_CONF_IPV6_RPL
  rpl_init();
#endif /* UIP_CONF_IPV6_RPL */

  while(1) {
    PROCESS_YIELD();
    eventhandler(ev, data);
  }

  PROCESS_END();
}
/*---------------------------------------------------------------------------*/


text:
// <copyright file="SortOrder.cs" company="natsnudasoft">
// Copyright (c) Adrian John Dunstan. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

namespace AdiePlayground.Data.Services
{
    /// <summary>
    /// Describes the order of sorting in a sort criterion.
    /// </summary>
    public enum SortOrder
    {
        /// <summary>
        /// Ascending sort order.
        /// </summary>
        Ascending = 0,

        /// <summary>
        /// Descending sort order.
        /// </summary>
        Descending = 1
    }
}

redpajama_set_name: RedPajamaGithub


text:
Chris-Git-Presentation
======================

But If I don't know how to use git, how am I going to get this off of github?

#Details
At the begining of the year I gave a presentation on git and github

#Links

http://gitref.org/index.html


text:
package yingyan

const (
	apiRootPath = `http://yingyan.baidu.com`

	entityAddPath      = `/api/v3/entity/add`
	entityDeletePath   = `/api/v3/entity/delete`
	entityUpdatePath   = `/api/v3/entity/update`
	entityList         = `/api/v3/entity/list`
	entitySearch       = `/api/v3/entity/search`
	entityAroundSearch = `/api/v3/entity/aroundsearch`
	entityBoundSearch  = `/api/v3/entity/boundsearch`

	trackAddPoint       = `/api/v3/track/addpoint`
	trackAddPoints      = `/api/v3/track/addpoints`
	trackGetLatestPoint = `/api/v3/track/getlatestpoint`
	trackGetDistance    = `/api/v3/track/getdistance`
	trackGetTrack       = `/api/v3/track/gettrack`

	analysisStaypoint = `/api/v3/analysis/staypoint`
)


text:
package org.apereo.portal.character.stream.events;

/** */
public interface PortletContentPlaceholderEvent extends PortletPlaceholderEvent {}


text:
"""
    SoftLayer.tests.CLI.modules.call_api_tests
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    :license: MIT, see LICENSE for more details.
"""
from SoftLayer import testing

import json

class CallCliTests(testing.TestCase):

    def test_options(self):
        mock = self.set_mock('SoftLayer_Service', 'method')
        mock.return_value = 'test'

        result = self.run_command(['call-api', 'Service', 'method',
                                   '--mask=some.mask',
                                   '--limit=20',
                                   '--offset=40',
                                   '--id=100'])

        self.assertEqual(result.exit_code, 0)
        self.assertEqual(json.loads(result.output), 'test')
        self.assert_called_with('SoftLayer_Service', 'method',
                                mask='mask[some.mask]',
                                limit=20,
                                offset=40,
                                identifier='100')

    def test_object(self):
        mock = self.set_mock('SoftLayer_Service', 'method')
        mock.return_value = {'string': 'string',
                             'int': 10,
                             'float': 1.0,
                             'None': None,
                             'Bool': True}

        result = self.run_command(['call-api', 'Service', 'method'])

        self.assertEqual(result.exit_code, 0)
        self.assertEqual(json.loads(result.output),
                         {'string': 'string',
                          'int': 10,
                          'float': 1.0,
                          'None': None,
                          'Bool': True})

    def test_object_table(self):
        mock = self.set_mock('SoftLayer_Service', 'method')
        mock.return_value = {'string': 'string',
                             'int': 10,
                             'float': 1.0,
                             'None': None,
                             'Bool': True}

        result = self.run_command(['call-api', 'Service', 'method'],
                                  fmt='table')

        self.assertEqual(result.exit_code, 0)
        # NOTE(kmcdonald): Order is not guaranteed
        self.assertIn(":........:........:", result.output)
        self.assertIn(":   Name : Value  :", result.output)
        self.assertIn(":    int : 10     :", result.output)
        self.assertIn(":   None : None   :", result.output)
        self.assertIn(":  float : 1.0    :", result.output)
        self.assertIn(":   Bool : True   :", result.output)
        self.assertIn(": string : string :", result.output)
        self.assertIn(":........:........:", result.output)

    def test_object_nested(self):
        mock = self.set_mock('SoftLayer_Service', 'method')
        mock.return_value = {'this': {'is': [{'pretty': 'nested'}]}}

        result = self.run_command(['call-api', 'Service', 'method'])

        self.assertEqual(result.exit_code, 0)
        self.assertEqual(json.loads(result.output),
                         {'this': {'is': [{'pretty': 'nested'}]}})

    def test_list(self):
        mock = self.set_mock('SoftLayer_Service', 'method')
        mock.return_value = [{'string': 'string',
                              'int': 10,
                              'float': 1.0,
                              'None': None,
                              'Bool': True}]

        result = self.run_command(['call-api', 'Service', 'method'])

        self.assertEqual(result.exit_code, 0)
        self.assertEqual(json.loads(result.output),
                         [{'string': 'string',
                           'int': 10,
                           'float': 1.0,
                           'None': None,
                           'Bool': True}])

    def test_list_table(self):
        mock = self.set_mock('SoftLayer_Service', 'method')
        mock.return_value = [{'string': 'string',
                              'int': 10,
                              'float': 1.0,
                              'None': None,
                              'Bool': True}]

        result = self.run_command(['call-api', 'Service', 'method'],
                                  fmt='table')

        self.assertEqual(result.exit_code, 0)
        self.assertEqual(result.output,
                         """:......:......:.......:.....:........:
: Bool : None : float : int : string :
:......:......:.......:.....:........:
: True : None :  1.0  :  10 : string :
:......:......:.......:.....:........:
""")

    def test_parameters(self):
        mock = self.set_mock('SoftLayer_Service', 'method')
        mock.return_value = {}

        result = self.run_command(['call-api', 'Service', 'method',
                                   'arg1', '1234'])

        self.assertEqual(result.exit_code, 0)
        self.assert_called_with('SoftLayer_Service', 'method',
                                args=('arg1', '1234'))


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/edgecontainer/v1/resources.proto

package com.google.cloud.edgecontainer.v1;

public interface MaintenanceWindowOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.edgecontainer.v1.MaintenanceWindow)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Configuration of a recurring maintenance window.
   *

   *
   * .google.cloud.edgecontainer.v1.RecurringTimeWindow recurring_window = 1;
   *
   * @return Whether the recurringWindow field is set.
   */
  boolean hasRecurringWindow();
  /**
   *
   *
   *

   * Configuration of a recurring maintenance window.
   *

   *
   * .google.cloud.edgecontainer.v1.RecurringTimeWindow recurring_window = 1;
   *
   * @return The recurringWindow.
   */
  com.google.cloud.edgecontainer.v1.RecurringTimeWindow getRecurringWindow();
  /**
   *
   *
   *

   * Configuration of a recurring maintenance window.
   *

   *
   * .google.cloud.edgecontainer.v1.RecurringTimeWindow recurring_window = 1;
   */
  com.google.cloud.edgecontainer.v1.RecurringTimeWindowOrBuilder getRecurringWindowOrBuilder();
}


text:
package jp.tf_web.radiolink.billing;

import jp.tf_web.radiolink.billing.util.IabResult;
import jp.tf_web.radiolink.billing.util.Inventory;
import jp.tf_web.radiolink.billing.util.Purchase;

/**
 * Created by furukawanobuyuki on 2015/12/30.
 */
public interface InAppBillingUtilListener {

    /** セットアップ結果の通知
     *
     * @param result
     */
    public void onIabSetupFinished(IabResult result);

    /** 購入済みアイテムの取得結果の通知
     *
     * @param result
     * @param inv
     */
    public void onQueryInventoryFinished(IabResult result, Inventory inv);

    /** 購入完了 結果の通知
     *
     * @param result
     * @param purchase
     */
    public void onIabPurchaseFinished(IabResult result, Purchase purchase);
}


text:
namespace Nancy.ViewEngines.Spark.Descriptors
{
    using System.Collections.Generic;

    public interface IDescriptorFilter
    {
        /// <summary>
        /// Called frequently to extract filter-specific parameters from a request context. This call
        /// happens on every request so should be implemented as efficiently as possible.
        /// </summary>
        /// <param name="context">The current request's action context</param>
        /// <param name="extra">Dictionary where additional parameters should be added</param>
        void ExtraParameters(ActionContext context, IDictionary<string, object> extra);

        /// <summary>
        /// The DefaultDescriptorBuider calls this method for the filter to return a modified enumerable
        /// ordered list of potential template locations. This is called only when the unique combination of action,
        /// master, view, and extra have not been resolved previously.
        /// </summary>
        /// <param name="locations">incoming ordered list of locations</param>
        /// <param name="extra">extra parameters which have been extracted</param>
        /// <returns>either the original list or a new, augmented, enumerable list</returns>
        IEnumerable<string> PotentialLocations(IEnumerable<string> locations, IDictionary<string, object> extra);
    }
}


text:
using DeviceSQL.Device.ROC.Data;
using DeviceSQL.Devices.Device.ROC.Data;
using Microsoft.SqlServer.Server;
using System;
using System.Data.SqlTypes;
using System.IO;
using System.Linq;

#endregion

namespace DeviceSQL.SQLTypes.ROCMaster
{
    [Serializable()]
    [SqlUserDefinedType(Format.UserDefined, IsByteOrdered = false, IsFixedLength = false, MaxByteSize = 27)]
    public struct ROCMaster_ROCPlusEventRecord : INullable, IBinarySerialize
    {

        #region Fields

        private byte[] data;

        #endregion

        #region Properties

        public bool IsNull
        {
            get;
            internal set;
        }

        public static ROCMaster_ROCPlusEventRecord Null
        {
            get
            {
                return new ROCMaster_ROCPlusEventRecord() { IsNull = true };
            }
        }

        public byte[] Data
        {
            get
            {
                if (data == null)
                {
                    data = new byte[22];
                }
                return data;
            }

            internal set
            {
                data = value;
            }
        }

        public int Index
        {
            get;
            internal set;
        }

        public SqlDateTime DateTimeStamp
        {
            get
            {
                var dateTimeStamp = new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).DateTimeStamp;
                return dateTimeStamp.HasValue ? dateTimeStamp.Value : SqlDateTime.Null;
            }
        }

        public SqlString EventType
        {
            get
            {
                return new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).EventType.ToString();
            }
        }

        public SqlString EventCode
        {
            get
            {
                var eventCode = new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).EventCode;
                return eventCode.HasValue ? eventCode.Value.ToString() : SqlString.Null;
            }
        }

        public string OperatorId
        {
            get
            {
                return new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).OperatorId;
            }
        }

        internal Tlp Tlp
        {
            get
            {
                return new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).Tlp;
            }
        }

        public SqlByte PointType
        {
            get
            {
                return Tlp.PointType;
            }
        }

        public SqlByte LogicalNumber
        {
            get
            {
                return Tlp.LogicalNumber;
            }
        }

        public SqlByte Parameter
        {
            get
            {
                return Tlp.Parameter;
            }
        }

        public SqlString DataType
        {
            get
            {
                var dataType = new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).DataType;
                return dataType.HasValue ? dataType.Value.ToString() : SqlString.Null;
            }
        }

        public SqlBinary OldValue
        {
            get
            {
                return new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).OldValue;
            }
        }

        public SqlBinary NewValue
        {
            get
            {
                return new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).NewValue;
            }
        }

        public SqlInt32 Spare
        {
            get
            {
                return new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).Spare;
            }
        }

        public SqlString Description
        {
            get
            {
                return new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).Description;
            }
        }

        public SqlByte FstNumber
        {
            get
            {
                var fstNumber = new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).FstNumber;
                return fstNumber.HasValue ? fstNumber.Value : SqlByte.Null;
            }
        }

        public SqlSingle FstValue
        {
            get
            {
                var fstValue = new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).FstValue;
                return fstValue.HasValue ? fstValue.Value : SqlSingle.Null;
            }
        }

        public SqlDateTime DateTimeValue
        {
            get
            {
                var dateTimeValue = new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).DateTimeValue;
                return dateTimeValue.HasValue ? dateTimeValue.Value : SqlDateTime.Null;
            }
        }

        public SqlSingle CalibrationRawValue
        {
            get
            {
                var calibrationRawValue = new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).CalibrationRawValue;
                return calibrationRawValue.HasValue ? calibrationRawValue.Value : SqlSingle.Null;
            }
        }

        public SqlSingle CalibrationCalibratedValue
        {
            get
            {
                var calibrationCalibratedValue = new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).CalibrationCalibratedValue;
                return calibrationCalibratedValue.HasValue ? calibrationCalibratedValue.Value : SqlSingle.Null;
            }
        }

        public ROCMaster_Parameter OldParameterValue
        {
            get
            {
                if (!PointType.IsNull && !Parameter.IsNull)
                {
                    switch (new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).DataType)
                    {
                        case ParameterType.AC3:
                            return new ROCMaster_Parameter() { RawType = ParameterType.AC3, RawValue = OldValue.Value.Take(3).ToArray() };
                        case ParameterType.BIN:
                            return new ROCMaster_Parameter() { RawType = ParameterType.BIN, RawValue = OldValue.Value.Take(1).ToArray() };
                        case ParameterType.FL:
                            return new ROCMaster_Parameter() { RawType = ParameterType.FL, RawValue = OldValue.Value };
                        case ParameterType.INT16:
                            return new ROCMaster_Parameter() { RawType = ParameterType.INT16, RawValue = OldValue.Value.Take(2).ToArray() };
                        case ParameterType.INT32:
                            return new ROCMaster_Parameter() { RawType = ParameterType.INT32, RawValue = OldValue.Value };
                        case ParameterType.INT8:
                            return new ROCMaster_Parameter() { RawType = ParameterType.INT8, RawValue = OldValue.Value.Take(1).ToArray() };
                        case ParameterType.TLP:
                            return new ROCMaster_Parameter() { RawType = ParameterType.TLP, RawValue = OldValue.Value.Take(3).ToArray() };
                        case ParameterType.UINT16:
                            return new ROCMaster_Parameter() { RawType = ParameterType.UINT16, RawValue = OldValue.Value.Take(2).ToArray() };
                        case ParameterType.UINT32:
                            return new ROCMaster_Parameter() { RawType = ParameterType.UINT32, RawValue = OldValue.Value };
                        case ParameterType.TIME:
                            return new ROCMaster_Parameter() { RawType = ParameterType.TIME, RawValue = OldValue.Value };
                        case ParameterType.UINT8:
                            return new ROCMaster_Parameter() { RawType = ParameterType.UINT8, RawValue = OldValue.Value.Take(1).ToArray() };
                        default:
                            return ROCMaster_Parameter.Null;
                    }
                }
                else
                {
                    return ROCMaster_Parameter.Null;
                }
            }
        }

        public ROCMaster_Parameter NewParameterValue
        {
            get
            {
                if (!PointType.IsNull && !Parameter.IsNull)
                {
                    switch (new Device.ROC.Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).DataType)
                    {
                        case ParameterType.AC3:
                            return new ROCMaster_Parameter() { RawType = ParameterType.AC3, RawValue = NewValue.Value.Take(3).ToArray() };
                        case ParameterType.AC7:
                            return new ROCMaster_Parameter() { RawType = ParameterType.AC7, RawValue = NewValue.Value.Union(new byte[3]).ToArray() };
                        case ParameterType.AC10:
                            return new ROCMaster_Parameter() { RawType = ParameterType.AC10, RawValue = NewValue.Value.Union(OldValue.Value).Union(BitConverter.GetBytes(Convert.ToUInt16(Spare.Value))).ToArray() };
                        case ParameterType.AC12:
                            return new ROCMaster_Parameter() { RawType = ParameterType.AC12, RawValue = NewValue.Value.Union(OldValue.Value).Union(BitConverter.GetBytes(Convert.ToUInt16(Spare.Value))).Union(new byte[2]).ToArray() };
                        case ParameterType.AC20:
                            return new ROCMaster_Parameter() { RawType = ParameterType.AC20, RawValue = NewValue.Value.Union(OldValue.Value).Union(BitConverter.GetBytes(Convert.ToUInt16(Spare.Value))).Union(new byte[10]).ToArray() };
                        case ParameterType.AC30:
                            return new ROCMaster_Parameter() { RawType = ParameterType.AC30, RawValue = NewValue.Value.Union(OldValue.Value).Union(BitConverter.GetBytes(Convert.ToUInt16(Spare.Value))).Union(new byte[20]).ToArray() };
                        case ParameterType.AC40:
                            return new ROCMaster_Parameter() { RawType = ParameterType.AC40, RawValue = NewValue.Value.Union(OldValue.Value).Union(BitConverter.GetBytes(Convert.ToUInt16(Spare.Value))).Union(new byte[30]).ToArray() };
                        case ParameterType.BIN:
                            return new ROCMaster_Parameter() { RawType = ParameterType.BIN, RawValue = NewValue.Value.Take(1).ToArray() };
                        case ParameterType.FL:
                            return new ROCMaster_Parameter() { RawType = ParameterType.FL, RawValue = NewValue.Value };
                        case ParameterType.DOUBLE:
                            return new ROCMaster_Parameter() { RawType = ParameterType.DOUBLE, RawValue = NewValue.Value.Union(OldValue.Value).ToArray() };
                        case ParameterType.INT16:
                            return new ROCMaster_Parameter() { RawType = ParameterType.INT16, RawValue = NewValue.Value.Take(2).ToArray() };
                        case ParameterType.INT32:
                            return new ROCMaster_Parameter() { RawType = ParameterType.INT32, RawValue = NewValue.Value };
                        case ParameterType.INT8:
                            return new ROCMaster_Parameter() { RawType = ParameterType.INT8, RawValue = NewValue.Value.Take(1).ToArray() };
                        case ParameterType.TLP:
                            return new ROCMaster_Parameter() { RawType = ParameterType.TLP, RawValue = NewValue.Value.Take(3).ToArray() };
                        case ParameterType.UINT16:
                            return new ROCMaster_Parameter() { RawType = ParameterType.UINT16, RawValue = NewValue.Value.Take(2).ToArray() };
                        case ParameterType.UINT32:
                            return new ROCMaster_Parameter() { RawType = ParameterType.UINT32, RawValue = NewValue.Value };
                        case ParameterType.TIME:
                            return new ROCMaster_Parameter() { RawType = ParameterType.TIME, RawValue = NewValue.Value };
                        case ParameterType.UINT8:
                            return new ROCMaster_Parameter() { RawType = ParameterType.UINT8, RawValue = NewValue.Value.Take(1).ToArray() };
                        default:
                            return ROCMaster_Parameter.Null;
                    }
                }
                else
                {
                    return ROCMaster_Parameter.Null;
                }
            }
        }

        #endregion

        #region Helper Methods

        public static ROCMaster_ROCPlusEventRecord Parse(SqlString stringToParse)
        {
            var parsedEventRecord = stringToParse.Value.Split(",".ToCharArray());
            var base64Bytes = Convert.FromBase64String(parsedEventRecord[1]);
            if (base64Bytes.Length == 22)
            {
                return new ROCMaster_ROCPlusEventRecord() { Index = ushort.Parse(parsedEventRecord[0]), Data = base64Bytes };
            }
            else
            {
                throw new ArgumentException("Input must be exactly 22 bytes");
            }
        }

        public override string ToString()
        {
            return string.Format("{0},{1}", Index, Convert.ToBase64String(Data));
        }

        #endregion

        #region Serialization Methods

        public void Read(BinaryReader binaryReader)
        {
            IsNull = binaryReader.ReadBoolean();
            Index = binaryReader.ReadInt32();
            if (!IsNull)
            {
                Data = binaryReader.ReadBytes(22);
            }
        }

        public void Write(BinaryWriter binaryWriter)
        {
            binaryWriter.Write(IsNull);
            binaryWriter.Write(Index);
            if (!IsNull)
            {
                binaryWriter.Write(Data, 0, 22);
            }
        }

        #endregion

    }
}


text:
namespace Leak.Networking.Core
{
    /// <summary>
    /// Describes the way how the incoming messages should be handled.
    /// </summary>
    public interface NetworkIncomingMessageHandler
    {
        /// <summary>
        /// Called when there is a payload with at least one byte.
        /// </summary>
        /// <param name="message">The incoming message containing the payload.</param>
        void OnMessage(NetworkIncomingMessage message);

        /// <summary>
        /// Called when the channel was disconnected and is not able to send or
        /// receive more messages. The callers should not use this channel any more.
        /// </summary>
        void OnDisconnected();
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>TEDx University of Dundee - Make a difference</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/style.css" rel="stylesheet">

    <link href="font-awesome-4.2.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">

    <link href="http://assets2.tedcdn.com/favicon.ico" rel="shortcut icon" />

                <button type="button" class="navbar-toggle pull-right" data-toggle="collapse" data-target=".navbar-main-collapse">

                </button>

                        About

                        Team

                        Speakers

                        Venue

                        Tickets

                        Partners

MAKE A DIFFERENCE

Saturday 23rd May 2015

TED: Ideas Worth Spreading

TED is a non-profit organization devoted to Ideas Worth
                    Spreading. Started as a four-day conference in California
                    30 years ago, TED has grown to support its mission with
                    multiple initiatives. The two annual TED Conferences invite
                    the world's leading thinkers and doers to speak for 18
                    minutes or less. Many of these talks are then made
                    available, free, at  ted.com

TEDx, x = Independently Organized Event

In the spirit of ideas worth spreading, TEDx is a program of
                    local, self-organized events that bring people together to
                    share a TED-like experience. At a TEDx event, TED Talks
                    video and live speakers combine to spark deep discussion and
                    connection.

TEDx University of Dundee

TEDx University Of Dundee is a student-led TEDx event, aiming
                    at inspiring new ideas and enhancing creativity among
                    university students and within the general public in Dundee.
                The upcoming event is the first TEDx organized at the
                    University of Dundee

Organizing Team

Dianbo Liu is the licence holder for the
                    upcoming TEDxUniversityofDundee event. He is the leader
                    of the team and is currently studying for a PhD within the
                    Computational and Physical Biology department at the
                    University of Dundee. He is interested in making links
                    among seemingly unrelated fields, and therefore come up
                    with innovative and useful inventions.

Gillian Dunphy was born and raised in Glasgow but was
                    compelled to make the lengthy journey to Dundee after being
                    lured by its East Coast charm. She is currently studying for
                    a PhD in Immunology at the University of Dundee. She is
                    currently managing a team of student volunteers in the areas
                    of Graphic Design and Stage Design. She is also involved in
                    marketing and speaker recruitment.

Stefan Tomov is a recent University of Dundee
                    graduate in the field of Economics and Politics. He comes
                    from Bulgaria and is currently the Deputy President of
                    Dundee University Students' Association (DUSA). Stefan is
                    responsible for securing the logistics required to make
                    TEDxUniversityofDundee a resounding success.

Thiago Britto-Borges is a Brazilian PhD student within the Computational Biology department of the University of Dundee
                    He has an inexhaustible passion for learning and enjoys spreading knowledge. Thiago
                    is responsible for developing and designing the TEDxUniversityofDundee website.

Sarah-Lena Offenburger is pursuing a PhD in
                    Neurobiology at the University of Dundee. When Sarah is not
                    in the lab, you will probably find her doing sports, taking
                    pictures or just having a coffee with friends. Sarah is a
                    curator within our team and is responsible for recruiting
                    and liasing with the speakers of the event.

Originally from Portugal, Fábio Madeira is
                    currently studying for a PhD within the Cell and Molecular
                    Biology department at the  University of Dundee,
                    specialising in Computational Biology. Alongside with Thiago, he helps managing and developing the website of the event.

Darya Baranovka is the president of  Enterprise
                    Gym which is a University of Dundee department where
                    students learn about entrepreneurship. She comes from the
                    small and pretty town of Liepaya, which is located on the
                    Latvian coast of the Baltic Sea. Darya is responsible for
                    the recruitment of volunteers and organising the logistics
                    of the event.

Kushal Rugjee moved from the island of
                    Mauritius to equally sunny Dundee to pursue a PhD in
                    Microbiology. His role in the team is to co-ordinate the
                    overall organisation of the TEDx event and to ensure that
                    progress is being made.

Sam Watkins is currently studying Computer Science at the University of Dundee.
                    He is in his third year now and interested in Web
                    Programming, Product Development and Entrepreneurship. Sam
                    is our Social Media Officer, taking care of our Twitter and
                    Facebook accounts.

Teodora Maghear is the Enterprise Assistant & Coordinator at the Enterprise Gym, University of Dundee.
                    Her perseverance and passion for entrepreneurship and innovation has seen her work her way up in the roles in the department.
                    She received her BSc in business Economics with marketing from Dundee University in 2014. Dora is actively contributing her
                    expertise in a number of areas of the project.

Alasdair McGill is Head of Enterprise &
                    Entrepreneurial Strategy at the University of Dundee.
                    Not a man to sit about, Alasdair has a brain that's always
                    busy and he loves thinking of creative ways to make a
                    difference. As well as his role at the university, Alasdair
                    is also a director and founder of several companies in
                    industries as diverse as retail, software, sports and
                    financial services. He is a formidable adviser within our team.

Yuri  Alexandrov is currently pursuing a master's
                    degree in Data Engineering. He studies Data because he likes
                    to observe and find patterns in the environment that
                    surrounds us. Yuri serves as a curator along with Sarah in
                    our team. He is involved in the recruitment of speakers.

Speakers

Speaker invitations are on their way! We also welcome
                    self-nominations from interested speakers.
                    Contact us at tedx@dundee.ac.uk for more details.

Venue

Lecture Theatre 3, Dalhousie Building

                   University of Dundee

                   Old Hawkhill, Dundee City DD1 5EN

Tickets

The event is open to both the general public and university
                    students and a total of one hundred tickets will be on sale.
                    Ticket sale will begin closer to the event's day.

Partners

          tedx@dundee.ac.uk

         Twitter

        Facebook

Dundee by Night by Mark Haldane

                Copyright © 2015 TEDxUniversityOfDundee. All rights reserved. This independent TEDx event is operated under license from TED.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>PollFulfillment (java-taxii API)</title>
<meta name="date" content="2014-10-08">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.mitre.taxii.messages.xml11

Class PollFulfillment

java.lang.Object

org.mitre.taxii.messages.xml11.MessageType

org.mitre.taxii.messages.xml11.RequestMessageType

org.mitre.taxii.messages.xml11.PollFulfillment

All Implemented Interfaces:

org.jvnet.jaxb2_commons.lang.Equals, org.jvnet.jaxb2_commons.lang.HashCode

public class PollFulfillment
extends RequestMessageType
implements org.jvnet.jaxb2_commons.lang.Equals, org.jvnet.jaxb2_commons.lang.HashCode

A request to to collect a prepared result set.

Java class for TAXIIPollFulfillmentType complex type.

The following schema fragment specifies the expected content contained within this class.

 <complexType name="TAXIIPollFulfillmentType">
   <complexContent>
     <extension base="{http://taxii.mitre.org/messages/taxii_xml_binding-1.1}RequestMessageType">
       <sequence>
         <element ref="{http://www.w3.org/2000/09/xmldsig#}Signature" minOccurs="0"/>
       </sequence>
       <attribute name="collection_name" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
       <attribute name="result_id" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
       <attribute name="result_part_number" type="{http://www.w3.org/2001/XMLSchema}positiveInteger" />
     </extension>
   </complexContent>
 </complexType>

Field Summary

Fields

Modifier and Type
Field and Description

protected java.lang.String
collectionName

protected java.lang.String
resultId

protected java.math.BigInteger
resultPartNumber

protected Signature
signature

Fields inherited from class org.mitre.taxii.messages.xml11.MessageType

extendedHeaders, messageId

Constructor Summary

Constructors

Constructor and Description

PollFulfillment()

Default no-arg constructor

PollFulfillment(ExtendedHeadersType extendedHeaders,
               java.lang.String messageId,
               Signature signature,
               java.lang.String collectionName,
               java.lang.String resultId,
               java.math.BigInteger resultPartNumber)

Fully-initialising value constructor

Method Summary

Methods

Modifier and Type
Method and Description

boolean
equals(java.lang.Object object)

boolean
equals(org.jvnet.jaxb2_commons.locator.ObjectLocator thisLocator,
      org.jvnet.jaxb2_commons.locator.ObjectLocator thatLocator,
      java.lang.Object object,
      org.jvnet.jaxb2_commons.lang.EqualsStrategy strategy)

java.lang.String
getCollectionName()

Gets the value of the collectionName property.

java.lang.String
getResultId()

Gets the value of the resultId property.

java.math.BigInteger
getResultPartNumber()

Gets the value of the resultPartNumber property.

Signature
getSignature()

An XML Digital Signature scoped to this message.

int
hashCode()

int
hashCode(org.jvnet.jaxb2_commons.locator.ObjectLocator locator,
        org.jvnet.jaxb2_commons.lang.HashCodeStrategy strategy)

void
setCollectionName(java.lang.String value)

Sets the value of the collectionName property.

void
setResultId(java.lang.String value)

Sets the value of the resultId property.

void
setResultPartNumber(java.math.BigInteger value)

Sets the value of the resultPartNumber property.

void
setSignature(Signature value)

Sets the value of the signature property.

PollFulfillment
withCollectionName(java.lang.String value)

PollFulfillment
withExtendedHeaders(ExtendedHeadersType value)

PollFulfillment
withMessageId(java.lang.String value)

PollFulfillment
withResultId(java.lang.String value)

PollFulfillment
withResultPartNumber(java.math.BigInteger value)

PollFulfillment
withSignature(Signature value)

Methods inherited from class org.mitre.taxii.messages.xml11.MessageType

getExtendedHeaders, getMessageId, setExtendedHeaders, setMessageId

Methods inherited from class java.lang.Object

clone, finalize, getClass, notify, notifyAll, toString, wait, wait, wait

Field Detail

signature

protected Signature signature

collectionName

protected java.lang.String collectionName

resultId

protected java.lang.String resultId

resultPartNumber

protected java.math.BigInteger resultPartNumber

Constructor Detail

PollFulfillment

public PollFulfillment()

Default no-arg constructor

PollFulfillment

public PollFulfillment(ExtendedHeadersType extendedHeaders,
               java.lang.String messageId,
               Signature signature,
               java.lang.String collectionName,
               java.lang.String resultId,
               java.math.BigInteger resultPartNumber)

Fully-initialising value constructor

Method Detail

getSignature

public Signature getSignature()

An XML Digital Signature scoped to this message.

Returns:

possible object is
     Signature

setSignature

public void setSignature(Signature value)

Sets the value of the signature property.

Parameters:

value - allowed object is
     Signature

getCollectionName

public java.lang.String getCollectionName()

Gets the value of the collectionName property.

Returns:

possible object is
     String

setCollectionName

public void setCollectionName(java.lang.String value)

Sets the value of the collectionName property.

Parameters:

value - allowed object is
     String

getResultId

public java.lang.String getResultId()

Gets the value of the resultId property.

Returns:

possible object is
     String

setResultId

public void setResultId(java.lang.String value)

Sets the value of the resultId property.

Parameters:

value - allowed object is
     String

getResultPartNumber

public java.math.BigInteger getResultPartNumber()

Gets the value of the resultPartNumber property.

Returns:

possible object is
     BigInteger

setResultPartNumber

public void setResultPartNumber(java.math.BigInteger value)

Sets the value of the resultPartNumber property.

Parameters:

value - allowed object is
     BigInteger

equals

public boolean equals(org.jvnet.jaxb2_commons.locator.ObjectLocator thisLocator,
             org.jvnet.jaxb2_commons.locator.ObjectLocator thatLocator,
             java.lang.Object object,
             org.jvnet.jaxb2_commons.lang.EqualsStrategy strategy)

Specified by:

equals in interface org.jvnet.jaxb2_commons.lang.Equals

Overrides:

equals in class RequestMessageType

equals

public boolean equals(java.lang.Object object)

Overrides:

equals in class RequestMessageType

hashCode

public int hashCode(org.jvnet.jaxb2_commons.locator.ObjectLocator locator,
           org.jvnet.jaxb2_commons.lang.HashCodeStrategy strategy)

Specified by:

hashCode in interface org.jvnet.jaxb2_commons.lang.HashCode

Overrides:

hashCode in class RequestMessageType

hashCode

public int hashCode()

Overrides:

hashCode in class RequestMessageType

withSignature

public PollFulfillment withSignature(Signature value)

withCollectionName

public PollFulfillment withCollectionName(java.lang.String value)

withResultId

public PollFulfillment withResultId(java.lang.String value)

withResultPartNumber

public PollFulfillment withResultPartNumber(java.math.BigInteger value)

withExtendedHeaders

public PollFulfillment withExtendedHeaders(ExtendedHeadersType value)

Overrides:

withExtendedHeaders in class RequestMessageType

withMessageId

public PollFulfillment withMessageId(java.lang.String value)

Overrides:

withMessageId in class RequestMessageType

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package info.smart.models.owc100

import java.time.OffsetDateTime
import java.time.format.DateTimeParseException

import com.typesafe.scalalogging.LazyLogging
import play.api.data.validation.ValidationError
import play.api.libs.json._

import scala.util.{Failure, Success, Try}

class TemporalExtentFormat extends Format[List[OffsetDateTime]] with LazyLogging {

  def reads(json: JsValue): JsResult[List[OffsetDateTime]] = {

    json match {
      case jsVal: JsString => parseDateJson(jsVal.toString()) match {
        case Success(date) if date.nonEmpty => {
          JsSuccess(date)
        }
        case Failure(ex) => {
          logger.error(s"JsError ValidationError ${ex.getLocalizedMessage}")
          JsError(Seq(JsPath() -> Seq(ValidationError("error.expected.iso8601date"),
            ValidationError("error.expected.iso8601interval"))))
        }
      }
      case _ => {
        logger.error("JsError ValidationError error.expected.datestring")
        JsError(Seq(JsPath() -> Seq(ValidationError("error.expected.datestring"))))
      }
    }
  }

  def parseDateJson(isoTemporalString: String): Try[List[OffsetDateTime]] = {
    if (isoTemporalString.contains("/")) {
      parseDateAsIntervalJson(isoTemporalString)
    } else {
      parseDateAsDateTimeJson(isoTemporalString)
    }
  }

  def parseDateAsIntervalJson(isoTemporalString: String): Try[List[OffsetDateTime]] = Try {
    val dateStrings = isoTemporalString.replace("\"", "").trim.split("/").toList
    val jsDates = for {
      jsd1 <- JsString(dateStrings.head).validate[OffsetDateTime]
      jsd2 <- JsString(dateStrings.last).validate[OffsetDateTime]
    } yield (jsd1, jsd2)
    jsDates match {
      case JsSuccess(a, b) => List(a._1, a._2)
      case JsError(errors) => {
        logger.error("JsError ValidationError error.expected.iso8601interval", errors)
        throw new DateTimeParseException("JsError ValidationError error.expected.iso8601interval", isoTemporalString, 0)
      }
    }
  }

  def parseDateAsDateTimeJson(isoTemporalString: String): Try[List[OffsetDateTime]] = Try {
    val jsDate = JsString(isoTemporalString.replace("\"", "").trim).validate[OffsetDateTime]
    jsDate match {
      case JsSuccess(date, path) =>  List(date)
      case JsError(errors) => {
        logger.error("JsError ValidationError error.expected.iso datestring", errors)
        throw new DateTimeParseException("JsError ValidationError error.expected.isodatestring", isoTemporalString, 0)
      }
    }
  }

  def writes(dateRange: List[OffsetDateTime]): JsValue = {
    val dates = dateRange.sortWith((a, b) => a.isBefore(b))
    if (dates.head == dates.last) {
      Json.toJson(dates.head)
    } else {
      val d1 = Json.toJson(dates.head)
      val d2 = Json.toJson(dates.last)
      JsString(d1.as[String] + "/" + d2.as[String])
    }
  }
}


text:
.. _terminology:

=====================
Terminology Reference
=====================

.. contents:: :local:
  :depth: 2

.. include:: /contents/contents-terminology.rst


text:
package org.apache.accumulo.server.master;

import static org.apache.accumulo.fate.zookeeper.ZooUtil.NodeMissingPolicy.SKIP;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.client.Instance;
import org.apache.accumulo.core.client.impl.thrift.ThriftSecurityException;
import org.apache.accumulo.core.conf.AccumuloConfiguration;
import org.apache.accumulo.core.data.KeyExtent;
import org.apache.accumulo.core.master.thrift.TabletServerStatus;
import org.apache.accumulo.core.tabletserver.thrift.NotServingTabletException;
import org.apache.accumulo.core.tabletserver.thrift.TabletClientService;
import org.apache.accumulo.core.util.AddressUtil;
import org.apache.accumulo.core.util.ServerServices;
import org.apache.accumulo.core.util.ThriftUtil;
import org.apache.accumulo.core.zookeeper.ZooUtil;
import org.apache.accumulo.server.master.state.TServerInstance;
import org.apache.accumulo.server.security.SystemCredentials;
import org.apache.accumulo.server.util.Halt;
import org.apache.accumulo.server.util.time.SimpleTimer;
import org.apache.accumulo.server.zookeeper.ZooCache;
import org.apache.accumulo.server.zookeeper.ZooLock;
import org.apache.accumulo.server.zookeeper.ZooReaderWriter;
import org.apache.accumulo.trace.instrument.Tracer;
import org.apache.hadoop.io.Text;
import org.apache.log4j.Logger;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransport;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.NoNodeException;
import org.apache.zookeeper.KeeperException.NotEmptyException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.data.Stat;

import com.google.common.net.HostAndPort;

public class LiveTServerSet implements Watcher {

  public interface Listener {
    void update(LiveTServerSet current, Set<TServerInstance> deleted, Set<TServerInstance> added);
  }

  private static final Logger log = Logger.getLogger(LiveTServerSet.class);

  private final Listener cback;
  private final Instance instance;
  private final AccumuloConfiguration conf;
  private ZooCache zooCache;

  public class TServerConnection {
    private final HostAndPort address;

    public TServerConnection(HostAndPort addr) throws TException {
      address = addr;
    }

    private String lockString(ZooLock mlock) {
      return mlock.getLockID().serialize(ZooUtil.getRoot(instance) + Constants.ZMASTER_LOCK);
    }

    public void assignTablet(ZooLock lock, KeyExtent extent) throws TException {
      TabletClientService.Client client = ThriftUtil.getClient(new TabletClientService.Client.Factory(), address, conf);
      try {
        client.loadTablet(Tracer.traceInfo(), SystemCredentials.get().toThrift(instance), lockString(lock), extent.toThrift());
      } finally {
        ThriftUtil.returnClient(client);
      }
    }

    public void unloadTablet(ZooLock lock, KeyExtent extent, boolean save) throws TException {
      TabletClientService.Client client = ThriftUtil.getClient(new TabletClientService.Client.Factory(), address, conf);
      try {
        client.unloadTablet(Tracer.traceInfo(), SystemCredentials.get().toThrift(instance), lockString(lock), extent.toThrift(), save);
      } finally {
        ThriftUtil.returnClient(client);
      }
    }

    public TabletServerStatus getTableMap(boolean usePooledConnection) throws TException, ThriftSecurityException {

      if (usePooledConnection == true)
        throw new UnsupportedOperationException();

      TTransport transport = ThriftUtil.createTransport(address, conf);

      try {
        TabletClientService.Client client = ThriftUtil.createClient(new TabletClientService.Client.Factory(), transport);
        return client.getTabletServerStatus(Tracer.traceInfo(), SystemCredentials.get().toThrift(instance));
      } finally {
        if (transport != null)
          transport.close();
      }
    }

    public void halt(ZooLock lock) throws TException, ThriftSecurityException {
      TabletClientService.Client client = ThriftUtil.getClient(new TabletClientService.Client.Factory(), address, conf);
      try {
        client.halt(Tracer.traceInfo(), SystemCredentials.get().toThrift(instance), lockString(lock));
      } finally {
        ThriftUtil.returnClient(client);
      }
    }

    public void fastHalt(ZooLock lock) throws TException {
      TabletClientService.Client client = ThriftUtil.getClient(new TabletClientService.Client.Factory(), address, conf);
      try {
        client.fastHalt(Tracer.traceInfo(), SystemCredentials.get().toThrift(instance), lockString(lock));
      } finally {
        ThriftUtil.returnClient(client);
      }
    }

    public void flush(ZooLock lock, String tableId, byte[] startRow, byte[] endRow) throws TException {
      TabletClientService.Client client = ThriftUtil.getClient(new TabletClientService.Client.Factory(), address, conf);
      try {
        client.flush(Tracer.traceInfo(), SystemCredentials.get().toThrift(instance), lockString(lock), tableId,
            startRow == null ? null : ByteBuffer.wrap(startRow), endRow == null ? null : ByteBuffer.wrap(endRow));
      } finally {
        ThriftUtil.returnClient(client);
      }
    }

    public void chop(ZooLock lock, KeyExtent extent) throws TException {
      TabletClientService.Client client = ThriftUtil.getClient(new TabletClientService.Client.Factory(), address, conf);
      try {
        client.chop(Tracer.traceInfo(), SystemCredentials.get().toThrift(instance), lockString(lock), extent.toThrift());
      } finally {
        ThriftUtil.returnClient(client);
      }
    }

    public void splitTablet(ZooLock lock, KeyExtent extent, Text splitPoint) throws TException, ThriftSecurityException, NotServingTabletException {
      TabletClientService.Client client = ThriftUtil.getClient(new TabletClientService.Client.Factory(), address, conf);
      try {
        client.splitTablet(Tracer.traceInfo(), SystemCredentials.get().toThrift(instance), extent.toThrift(),
            ByteBuffer.wrap(splitPoint.getBytes(), 0, splitPoint.getLength()));
      } finally {
        ThriftUtil.returnClient(client);
      }
    }

    public void flushTablet(ZooLock lock, KeyExtent extent) throws TException {
      TabletClientService.Client client = ThriftUtil.getClient(new TabletClientService.Client.Factory(), address, conf);
      try {
        client.flushTablet(Tracer.traceInfo(), SystemCredentials.get().toThrift(instance), lockString(lock), extent.toThrift());
      } finally {
        ThriftUtil.returnClient(client);
      }
    }

    public void compact(ZooLock lock, String tableId, byte[] startRow, byte[] endRow) throws TException {
      TabletClientService.Client client = ThriftUtil.getClient(new TabletClientService.Client.Factory(), address, conf);
      try {
        client.compact(Tracer.traceInfo(), SystemCredentials.get().toThrift(instance), lockString(lock), tableId,
            startRow == null ? null : ByteBuffer.wrap(startRow), endRow == null ? null : ByteBuffer.wrap(endRow));
      } finally {
        ThriftUtil.returnClient(client);
      }
    }

    public boolean isActive(long tid) throws TException {
      TabletClientService.Client client = ThriftUtil.getClient(new TabletClientService.Client.Factory(), address, conf);
      try {
        return client.isActive(Tracer.traceInfo(), tid);
      } finally {
        ThriftUtil.returnClient(client);
      }
    }

  }

  static class TServerInfo {
    TServerConnection connection;
    TServerInstance instance;

    TServerInfo(TServerInstance instance, TServerConnection connection) {
      this.connection = connection;
      this.instance = instance;
    }
  };

  // The set of active tservers with locks, indexed by their name in zookeeper
  private Map<String,TServerInfo> current = new HashMap<String,TServerInfo>();
  // as above, indexed by TServerInstance
  private Map<TServerInstance,TServerInfo> currentInstances = new HashMap<TServerInstance,TServerInfo>();

  // The set of entries in zookeeper without locks, and the first time each was noticed
  private Map<String,Long> locklessServers = new HashMap<String,Long>();

  public LiveTServerSet(Instance instance, AccumuloConfiguration conf, Listener cback) {
    this.cback = cback;
    this.instance = instance;
    this.conf = conf;

  }

  public synchronized ZooCache getZooCache() {
    if (zooCache == null)
      zooCache = new ZooCache(this);
    return zooCache;
  }

  public synchronized void startListeningForTabletServerChanges() {
    scanServers();
    SimpleTimer.getInstance(conf).schedule(new Runnable() {
      @Override
      public void run() {
        scanServers();
      }
    }, 0, 5000);
  }

  public synchronized void scanServers() {
    try {
      final Set<TServerInstance> updates = new HashSet<TServerInstance>();
      final Set<TServerInstance> doomed = new HashSet<TServerInstance>();

      final String path = ZooUtil.getRoot(instance) + Constants.ZTSERVERS;

      HashSet<String> all = new HashSet<String>(current.keySet());
      all.addAll(getZooCache().getChildren(path));

      locklessServers.keySet().retainAll(all);

      for (String zPath : all) {
        checkServer(updates, doomed, path, zPath);
      }

      // log.debug("Current: " + current.keySet());
      if (!doomed.isEmpty() || !updates.isEmpty())
        this.cback.update(this, doomed, updates);
    } catch (Exception ex) {
      log.error(ex, ex);
    }
  }

  private void deleteServerNode(String serverNode) throws InterruptedException, KeeperException {
    try {
      ZooReaderWriter.getInstance().delete(serverNode, -1);
    } catch (NotEmptyException ex) {
      // race condition: tserver created the lock after our last check; we'll see it at the next check
    } catch (NoNodeException nne) {
      // someone else deleted it
    }
  }

  private synchronized void checkServer(final Set<TServerInstance> updates, final Set<TServerInstance> doomed, final String path, final String zPath)
      throws TException, InterruptedException, KeeperException {

    TServerInfo info = current.get(zPath);

    final String lockPath = path + "/" + zPath;
    Stat stat = new Stat();
    byte[] lockData = ZooLock.getLockData(getZooCache(), lockPath, stat);

    if (lockData == null) {
      if (info != null) {
        doomed.add(info.instance);
        current.remove(zPath);
        currentInstances.remove(info.instance);
      }

      Long firstSeen = locklessServers.get(zPath);
      if (firstSeen == null) {
        locklessServers.put(zPath, System.currentTimeMillis());
      } else if (System.currentTimeMillis() - firstSeen > 10 * 60 * 1000) {
        deleteServerNode(path + "/" + zPath);
        locklessServers.remove(zPath);
      }
    } else {
      locklessServers.remove(zPath);
      ServerServices services = new ServerServices(new String(lockData, StandardCharsets.UTF_8));
      HostAndPort client = services.getAddress(ServerServices.Service.TSERV_CLIENT);
      TServerInstance instance = new TServerInstance(client, stat.getEphemeralOwner());

      if (info == null) {
        updates.add(instance);
        TServerInfo tServerInfo = new TServerInfo(instance, new TServerConnection(client));
        current.put(zPath, tServerInfo);
        currentInstances.put(instance, tServerInfo);
      } else if (!info.instance.equals(instance)) {
        doomed.add(info.instance);
        updates.add(instance);
        TServerInfo tServerInfo = new TServerInfo(instance, new TServerConnection(client));
        current.put(zPath, tServerInfo);
        currentInstances.put(info.instance, tServerInfo);
      }
    }
  }

  @Override
  public void process(WatchedEvent event) {

    // its important that these event are propagated by ZooCache, because this ensures when reading zoocache that is has already processed the event and cleared
    // relevant nodes before code below reads from zoocache

    if (event.getPath() != null) {
      if (event.getPath().endsWith(Constants.ZTSERVERS)) {
        scanServers();
      } else if (event.getPath().contains(Constants.ZTSERVERS)) {
        int pos = event.getPath().lastIndexOf('/');

        // do only if ZTSERVER is parent
        if (pos >= 0 && event.getPath().substring(0, pos).endsWith(Constants.ZTSERVERS)) {

          String server = event.getPath().substring(pos + 1);

          final Set<TServerInstance> updates = new HashSet<TServerInstance>();
          final Set<TServerInstance> doomed = new HashSet<TServerInstance>();

          final String path = ZooUtil.getRoot(instance) + Constants.ZTSERVERS;

          try {
            checkServer(updates, doomed, path, server);
            if (!doomed.isEmpty() || !updates.isEmpty())
              this.cback.update(this, doomed, updates);
          } catch (Exception ex) {
            log.error(ex, ex);
          }
        }
      }
    }
  }

  public synchronized TServerConnection getConnection(TServerInstance server) {
    if (server == null)
      return null;
    TServerInfo tServerInfo = currentInstances.get(server);
    if (tServerInfo == null)
      return null;
    return tServerInfo.connection;
  }

  public synchronized Set<TServerInstance> getCurrentServers() {
    return new HashSet<TServerInstance>(currentInstances.keySet());
  }

  public synchronized int size() {
    return current.size();
  }

  public synchronized TServerInstance find(String tabletServer) {
    HostAndPort addr = AddressUtil.parseAddress(tabletServer, false);
    for (Entry<String,TServerInfo> entry : current.entrySet()) {
      if (entry.getValue().instance.getLocation().equals(addr))
        return entry.getValue().instance;
    }
    return null;
  }

  public synchronized void remove(TServerInstance server) {
    String zPath = null;
    for (Entry<String,TServerInfo> entry : current.entrySet()) {
      if (entry.getValue().instance.equals(server)) {
        zPath = entry.getKey();
        break;
      }
    }
    if (zPath == null)
      return;
    current.remove(zPath);
    currentInstances.remove(server);

    log.info("Removing zookeeper lock for " + server);
    String fullpath = ZooUtil.getRoot(instance) + Constants.ZTSERVERS + "/" + zPath;
    try {
      ZooReaderWriter.getRetryingInstance().recursiveDelete(fullpath, SKIP);
    } catch (Exception e) {
      String msg = "error removing tablet server lock";
      log.fatal(msg, e);
      Halt.halt(msg, -1);
    }
    getZooCache().clear(fullpath);
  }
}