private void populateRoutingRulestoSameNode(
      Ip4Address vmIp,
      MacAddress vmMac,
      PortNumber port,
      DeviceId deviceId,
      long vni,
      String cidr) {
    TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
    TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();

    // FIXME: we need to check the VNI of the dest IP also just in case...
    sBuilder
        .matchEthType(Ethernet.TYPE_IPV4)
        .matchIPDst(vmIp.toIpPrefix())
        .matchIPSrc(IpPrefix.valueOf(cidr))
        .matchTunnelId(vni);

    tBuilder.setEthDst(vmMac).setOutput(port);

    ForwardingObjective fo =
        DefaultForwardingObjective.builder()
            .withSelector(sBuilder.build())
            .withTreatment(tBuilder.build())
            .withPriority(EW_ROUTING_RULE_PRIORITY)
            .withFlag(ForwardingObjective.Flag.SPECIFIC)
            .fromApp(appId)
            .add();

    flowObjectiveService.forward(deviceId, fo);
  }
  /**
   * Creates and installs a new filtering objective for the specified device.
   *
   * @param appId application identifier
   * @param deviceId device identifier
   * @param stream filtering objective JSON
   * @return status of the request - CREATED if the JSON is correct, BAD_REQUEST if the JSON is
   *     invalid
   * @onos.rsModel FilteringObjective
   */
  @POST
  @Path("{deviceId}/filter")
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public Response createFilteringObjective(
      @QueryParam("appId") String appId,
      @PathParam("deviceId") String deviceId,
      InputStream stream) {
    try {
      UriBuilder locationBuilder = null;
      ObjectNode jsonTree = (ObjectNode) mapper().readTree(stream);
      if (validateDeviceId(deviceId, jsonTree)) {

        if (appId != null) {
          jsonTree.put("appId", appId);
        }

        DeviceId did = DeviceId.deviceId(deviceId);
        FilteringObjective filteringObjective =
            codec(FilteringObjective.class).decode(jsonTree, this);
        flowObjectiveService.filter(did, filteringObjective);
        locationBuilder =
            uriInfo
                .getBaseUriBuilder()
                .path("flowobjectives")
                .path(did.toString())
                .path("filter")
                .path(Integer.toString(filteringObjective.id()));
      }
      return Response.created(locationBuilder.build()).build();
    } catch (IOException e) {
      throw new IllegalArgumentException(e);
    }
  }
  private void populateRoutingRulestoDifferentNode(
      Ip4Address vmIp, long vni, DeviceId deviceId, Ip4Address hostIp, String cidr) {
    TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
    TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();

    sBuilder
        .matchEthType(Ethernet.TYPE_IPV4)
        .matchTunnelId(vni)
        .matchIPSrc(IpPrefix.valueOf(cidr))
        .matchIPDst(vmIp.toIpPrefix());
    tBuilder
        .extension(buildExtension(deviceService, deviceId, hostIp), deviceId)
        .setOutput(nodeService.tunnelPort(deviceId).get());

    ForwardingObjective fo =
        DefaultForwardingObjective.builder()
            .withSelector(sBuilder.build())
            .withTreatment(tBuilder.build())
            .withPriority(EW_ROUTING_RULE_PRIORITY)
            .withFlag(ForwardingObjective.Flag.SPECIFIC)
            .fromApp(appId)
            .add();

    flowObjectiveService.forward(deviceId, fo);
  }
 /**
  * Returns the globally unique nextId.
  *
  * @return 200 OK with next identifier
  * @onos.rsModel NextId
  */
 @GET
 @Path("next")
 @Produces(MediaType.APPLICATION_JSON)
 public Response getNextId() {
   root.put("nextId", flowObjectiveService.allocateNextId());
   return ok(root).build();
 }
  /**
   * Installs the filtering rules onto the specified device.
   *
   * @param stream filtering rule JSON
   * @return 200 OK
   * @onos.rsModel ObjectivePolicy
   */
  @POST
  @Path("policy")
  @Consumes(MediaType.APPLICATION_JSON)
  public Response initPolicy(InputStream stream) {

    try {
      ObjectNode jsonTree = (ObjectNode) mapper().readTree(stream);
      JsonNode policyJson = jsonTree.get("policy");

      if (policyJson == null || policyJson.asText().isEmpty()) {
        throw new IllegalArgumentException(POLICY_INVALID);
      }

      flowObjectiveService.initPolicy(policyJson.asText());
      return Response.ok().build();
    } catch (IOException e) {
      throw new IllegalArgumentException(e);
    }
  }
  private void populateRuleToGateway(DeviceId deviceId, GroupId groupId, long vni, String cidr) {
    TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
    TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();

    sBuilder
        .matchEthType(Ethernet.TYPE_IPV4)
        .matchTunnelId(vni)
        .matchIPSrc(IpPrefix.valueOf(cidr))
        .matchEthDst(Constants.DEFAULT_GATEWAY_MAC);

    tBuilder.group(groupId);
    ForwardingObjective fo =
        DefaultForwardingObjective.builder()
            .withSelector(sBuilder.build())
            .withTreatment(tBuilder.build())
            .withFlag(ForwardingObjective.Flag.SPECIFIC)
            .withPriority(ROUTING_RULE_PRIORITY)
            .fromApp(appId)
            .add();

    flowObjectiveService.forward(deviceId, fo);
  }
  private void populateGatewayIcmpRule(Ip4Address gatewayIp, DeviceId deviceId) {
    TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
    TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();

    sBuilder
        .matchEthType(Ethernet.TYPE_IPV4)
        .matchIPProtocol(IPv4.PROTOCOL_ICMP)
        .matchIPDst(gatewayIp.toIpPrefix());

    tBuilder.setOutput(PortNumber.CONTROLLER);

    ForwardingObjective fo =
        DefaultForwardingObjective.builder()
            .withSelector(sBuilder.build())
            .withTreatment(tBuilder.build())
            .withPriority(GATEWAY_ICMP_PRIORITY)
            .withFlag(ForwardingObjective.Flag.VERSATILE)
            .fromApp(appId)
            .add();

    flowObjectiveService.forward(deviceId, fo);
  }
  private void populateGatewayToController(long vni, String subNetCidr) {
    TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
    TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();

    sBuilder
        .matchEthType(Ethernet.TYPE_IPV4)
        .matchTunnelId(vni)
        .matchIPSrc(IpPrefix.valueOf(subNetCidr))
        .matchEthDst(Constants.DEFAULT_GATEWAY_MAC);
    tBuilder.setOutput(PortNumber.CONTROLLER);

    ForwardingObjective fo =
        DefaultForwardingObjective.builder()
            .withSelector(sBuilder.build())
            .withTreatment(tBuilder.build())
            .withFlag(ForwardingObjective.Flag.VERSATILE)
            .withPriority(ROUTING_RULE_PRIORITY)
            .fromApp(appId)
            .add();

    gatewayService
        .getGatewayDeviceIds()
        .forEach(deviceId -> flowObjectiveService.forward(deviceId, fo));
  }
  // Install a rule forwarding the packet to the specified port.
  private void installRule(PacketContext context, PortNumber portNumber) {
    //
    // We don't support (yet) buffer IDs in the Flow Service so
    // packet out first.
    //
    Ethernet inPkt = context.inPacket().parsed();
    TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();

    // If PacketOutOnly or ARP packet than forward directly to output port
    if (packetOutOnly || inPkt.getEtherType() == Ethernet.TYPE_ARP) {
      packetOut(context, portNumber);
      return;
    }

    //
    // If matchDstMacOnly
    //    Create flows matching dstMac only
    // Else
    //    Create flows with default matching and include configured fields
    //
    if (matchDstMacOnly) {
      selectorBuilder.matchEthDst(inPkt.getDestinationMAC());
    } else {
      selectorBuilder
          .matchInPort(context.inPacket().receivedFrom().port())
          .matchEthSrc(inPkt.getSourceMAC())
          .matchEthDst(inPkt.getDestinationMAC());

      // If configured Match Vlan ID
      if (matchVlanId && inPkt.getVlanID() != Ethernet.VLAN_UNTAGGED) {
        selectorBuilder.matchVlanId(VlanId.vlanId(inPkt.getVlanID()));
      }

      //
      // If configured and EtherType is IPv4 - Match IPv4 and
      // TCP/UDP/ICMP fields
      //
      if (matchIpv4Address && inPkt.getEtherType() == Ethernet.TYPE_IPV4) {
        IPv4 ipv4Packet = (IPv4) inPkt.getPayload();
        byte ipv4Protocol = ipv4Packet.getProtocol();
        Ip4Prefix matchIp4SrcPrefix =
            Ip4Prefix.valueOf(ipv4Packet.getSourceAddress(), Ip4Prefix.MAX_MASK_LENGTH);
        Ip4Prefix matchIp4DstPrefix =
            Ip4Prefix.valueOf(ipv4Packet.getDestinationAddress(), Ip4Prefix.MAX_MASK_LENGTH);
        selectorBuilder
            .matchEthType(Ethernet.TYPE_IPV4)
            .matchIPSrc(matchIp4SrcPrefix)
            .matchIPDst(matchIp4DstPrefix);

        if (matchIpv4Dscp) {
          byte dscp = ipv4Packet.getDscp();
          byte ecn = ipv4Packet.getEcn();
          selectorBuilder.matchIPDscp(dscp).matchIPEcn(ecn);
        }

        if (matchTcpUdpPorts && ipv4Protocol == IPv4.PROTOCOL_TCP) {
          TCP tcpPacket = (TCP) ipv4Packet.getPayload();
          selectorBuilder
              .matchIPProtocol(ipv4Protocol)
              .matchTcpSrc(tcpPacket.getSourcePort())
              .matchTcpDst(tcpPacket.getDestinationPort());
        }
        if (matchTcpUdpPorts && ipv4Protocol == IPv4.PROTOCOL_UDP) {
          UDP udpPacket = (UDP) ipv4Packet.getPayload();
          selectorBuilder
              .matchIPProtocol(ipv4Protocol)
              .matchUdpSrc(udpPacket.getSourcePort())
              .matchUdpDst(udpPacket.getDestinationPort());
        }
        if (matchIcmpFields && ipv4Protocol == IPv4.PROTOCOL_ICMP) {
          ICMP icmpPacket = (ICMP) ipv4Packet.getPayload();
          selectorBuilder
              .matchIPProtocol(ipv4Protocol)
              .matchIcmpType(icmpPacket.getIcmpType())
              .matchIcmpCode(icmpPacket.getIcmpCode());
        }
      }

      //
      // If configured and EtherType is IPv6 - Match IPv6 and
      // TCP/UDP/ICMP fields
      //
      if (matchIpv6Address && inPkt.getEtherType() == Ethernet.TYPE_IPV6) {
        IPv6 ipv6Packet = (IPv6) inPkt.getPayload();
        byte ipv6NextHeader = ipv6Packet.getNextHeader();
        Ip6Prefix matchIp6SrcPrefix =
            Ip6Prefix.valueOf(ipv6Packet.getSourceAddress(), Ip6Prefix.MAX_MASK_LENGTH);
        Ip6Prefix matchIp6DstPrefix =
            Ip6Prefix.valueOf(ipv6Packet.getDestinationAddress(), Ip6Prefix.MAX_MASK_LENGTH);
        selectorBuilder
            .matchEthType(Ethernet.TYPE_IPV6)
            .matchIPv6Src(matchIp6SrcPrefix)
            .matchIPv6Dst(matchIp6DstPrefix);

        if (matchIpv6FlowLabel) {
          selectorBuilder.matchIPv6FlowLabel(ipv6Packet.getFlowLabel());
        }

        if (matchTcpUdpPorts && ipv6NextHeader == IPv6.PROTOCOL_TCP) {
          TCP tcpPacket = (TCP) ipv6Packet.getPayload();
          selectorBuilder
              .matchIPProtocol(ipv6NextHeader)
              .matchTcpSrc(tcpPacket.getSourcePort())
              .matchTcpDst(tcpPacket.getDestinationPort());
        }
        if (matchTcpUdpPorts && ipv6NextHeader == IPv6.PROTOCOL_UDP) {
          UDP udpPacket = (UDP) ipv6Packet.getPayload();
          selectorBuilder
              .matchIPProtocol(ipv6NextHeader)
              .matchUdpSrc(udpPacket.getSourcePort())
              .matchUdpDst(udpPacket.getDestinationPort());
        }
        if (matchIcmpFields && ipv6NextHeader == IPv6.PROTOCOL_ICMP6) {
          ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
          selectorBuilder
              .matchIPProtocol(ipv6NextHeader)
              .matchIcmpv6Type(icmp6Packet.getIcmpType())
              .matchIcmpv6Code(icmp6Packet.getIcmpCode());
        }
      }
    }
    TrafficTreatment treatment = DefaultTrafficTreatment.builder().setOutput(portNumber).build();

    ForwardingObjective forwardingObjective =
        DefaultForwardingObjective.builder()
            .withSelector(selectorBuilder.build())
            .withTreatment(treatment)
            .withPriority(flowPriority)
            .withFlag(ForwardingObjective.Flag.VERSATILE)
            .fromApp(appId)
            .makeTemporary(flowTimeout)
            .add();

    flowObjectiveService.forward(context.inPacket().receivedFrom().deviceId(), forwardingObjective);

    //
    // If packetOutOfppTable
    //  Send packet back to the OpenFlow pipeline to match installed flow
    // Else
    //  Send packet direction on the appropriate port
    //
    if (packetOutOfppTable) {
      packetOut(context, PortNumber.TABLE);
    } else {
      packetOut(context, portNumber);
    }
  }