/**
   * Creates and installs a new forwarding objective for the specified device.
   *
   * @param appId application identifier
   * @param deviceId device identifier
   * @param stream forwarding objective JSON
   * @return status of the request - CREATED if the JSON is correct, BAD_REQUEST if the JSON is
   *     invalid
   * @onos.rsModel ForwardingObjective
   */
  @POST
  @Path("{deviceId}/forward")
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public Response createForwardingObjective(
      @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);
        ForwardingObjective forwardingObjective =
            codec(ForwardingObjective.class).decode(jsonTree, this);
        flowObjectiveService.forward(did, forwardingObjective);
        locationBuilder =
            uriInfo
                .getBaseUriBuilder()
                .path("flowobjectives")
                .path(did.toString())
                .path("forward")
                .path(Integer.toString(forwardingObjective.id()));
      }
      return Response.created(locationBuilder.build()).build();
    } catch (IOException e) {
      throw new IllegalArgumentException(e);
    }
  }
  private void installDownstreamRules(ForwardingObjective fwd) {
    List<Pair<Instruction, Instruction>> vlanOps =
        vlanOps(fwd, L2ModificationInstruction.L2SubType.VLAN_POP);

    if (vlanOps == null) {
      return;
    }

    Instruction output = fetchOutput(fwd, "downstream");

    if (output == null) {
      return;
    }

    Pair<Instruction, Instruction> popAndRewrite = vlanOps.remove(0);

    TrafficSelector selector = fwd.selector();

    Criterion outerVlan = selector.getCriterion(Criterion.Type.VLAN_VID);
    Criterion innerVlan = selector.getCriterion(Criterion.Type.INNER_VLAN_VID);
    Criterion inport = selector.getCriterion(Criterion.Type.IN_PORT);

    if (outerVlan == null || innerVlan == null || inport == null) {
      log.error("Forwarding objective is underspecified: {}", fwd);
      fail(fwd, ObjectiveError.BADPARAMS);
      return;
    }

    Criterion innerVid = Criteria.matchVlanId(((VlanIdCriterion) innerVlan).vlanId());

    FlowRule.Builder outer =
        DefaultFlowRule.builder()
            .forDevice(deviceId)
            .fromApp(appId)
            .makePermanent()
            .withPriority(fwd.priority())
            .withSelector(buildSelector(inport, outerVlan))
            .withTreatment(
                buildTreatment(popAndRewrite.getLeft(), Instructions.transition(QQ_TABLE)));

    FlowRule.Builder inner =
        DefaultFlowRule.builder()
            .forDevice(deviceId)
            .fromApp(appId)
            .forTable(QQ_TABLE)
            .makePermanent()
            .withPriority(fwd.priority())
            .withSelector(buildSelector(inport, innerVid))
            .withTreatment(buildTreatment(popAndRewrite.getLeft(), output));

    applyRules(fwd, inner, outer);
  }
  private boolean checkForMulticast(ForwardingObjective fwd) {

    VlanIdCriterion vlan =
        (VlanIdCriterion) filterForCriterion(fwd.selector().criteria(), Criterion.Type.VLAN_VID);

    return (vlan != null && vlan.vlanId().equals(VlanId.vlanId(MCAST_VLAN)));
  }
  private void installUpstreamRules(ForwardingObjective fwd) {
    List<Pair<Instruction, Instruction>> vlanOps =
        vlanOps(fwd, L2ModificationInstruction.L2SubType.VLAN_PUSH);

    if (vlanOps == null) {
      return;
    }

    Instruction output = fetchOutput(fwd, "upstream");

    if (output == null) {
      return;
    }

    Pair<Instruction, Instruction> innerPair = vlanOps.remove(0);

    Pair<Instruction, Instruction> outerPair = vlanOps.remove(0);

    FlowRule.Builder inner =
        DefaultFlowRule.builder()
            .forDevice(deviceId)
            .fromApp(appId)
            .makePermanent()
            .withPriority(fwd.priority())
            .withSelector(fwd.selector())
            .withTreatment(buildTreatment(innerPair.getRight(), Instructions.transition(QQ_TABLE)));

    PortCriterion inPort = (PortCriterion) fwd.selector().getCriterion(Criterion.Type.IN_PORT);

    VlanId cVlanId =
        ((L2ModificationInstruction.ModVlanIdInstruction) innerPair.getRight()).vlanId();

    FlowRule.Builder outer =
        DefaultFlowRule.builder()
            .forDevice(deviceId)
            .fromApp(appId)
            .forTable(QQ_TABLE)
            .makePermanent()
            .withPriority(fwd.priority())
            .withSelector(buildSelector(inPort, Criteria.matchVlanId(cVlanId)))
            .withTreatment(buildTreatment(outerPair.getLeft(), outerPair.getRight(), output));

    applyRules(fwd, inner, outer);
  }
  private void applyRules(ForwardingObjective fwd, FlowRule.Builder inner, FlowRule.Builder outer) {
    FlowRuleOperations.Builder builder = FlowRuleOperations.builder();
    switch (fwd.op()) {
      case ADD:
        builder.add(inner.build()).add(outer.build());
        break;
      case REMOVE:
        builder.remove(inner.build()).remove(outer.build());
        break;
      case ADD_TO_EXISTING:
        break;
      case REMOVE_FROM_EXISTING:
        break;
      default:
        log.warn("Unknown forwarding operation: {}", fwd.op());
    }

    applyFlowRules(builder, fwd);
  }
  private List<Pair<Instruction, Instruction>> vlanOps(
      ForwardingObjective fwd, L2ModificationInstruction.L2SubType type) {

    List<Pair<Instruction, Instruction>> vlanOps =
        findVlanOps(fwd.treatment().allInstructions(), type);

    if (vlanOps == null) {
      String direction =
          type == L2ModificationInstruction.L2SubType.VLAN_POP ? "downstream" : "upstream";
      log.error("Missing vlan operations in {} forwarding: {}", direction, fwd);
      fail(fwd, ObjectiveError.BADPARAMS);
      return null;
    }
    return vlanOps;
  }
  private Instruction fetchOutput(ForwardingObjective fwd, String direction) {
    Instruction output =
        fwd.treatment()
            .allInstructions()
            .stream()
            .filter(i -> i.type() == Instruction.Type.OUTPUT)
            .findFirst()
            .orElse(null);

    if (output == null) {
      log.error("OLT {} rule has no output", direction);
      fail(fwd, ObjectiveError.BADPARAMS);
      return null;
    }
    return output;
  }
  @Override
  public void forward(ForwardingObjective fwd) {

    if (checkForMulticast(fwd)) {
      processMulticastRule(fwd);
      return;
    }

    TrafficTreatment treatment = fwd.treatment();

    List<Instruction> instructions = treatment.allInstructions();

    Optional<Instruction> vlanIntruction =
        instructions
            .stream()
            .filter(i -> i.type() == Instruction.Type.L2MODIFICATION)
            .filter(
                i ->
                    ((L2ModificationInstruction) i).subtype()
                            == L2ModificationInstruction.L2SubType.VLAN_PUSH
                        || ((L2ModificationInstruction) i).subtype()
                            == L2ModificationInstruction.L2SubType.VLAN_POP)
            .findAny();

    if (!vlanIntruction.isPresent()) {
      fail(fwd, ObjectiveError.BADPARAMS);
      return;
    }

    L2ModificationInstruction vlanIns = (L2ModificationInstruction) vlanIntruction.get();

    if (vlanIns.subtype() == L2ModificationInstruction.L2SubType.VLAN_PUSH) {
      installUpstreamRules(fwd);
    } else if (vlanIns.subtype() == L2ModificationInstruction.L2SubType.VLAN_POP) {
      installDownstreamRules(fwd);
    } else {
      log.error("Unknown OLT operation: {}", fwd);
      fail(fwd, ObjectiveError.UNSUPPORTED);
      return;
    }

    pass(fwd);
  }
  private void processMulticastRule(ForwardingObjective fwd) {
    if (fwd.nextId() == null) {
      log.error("Multicast objective does not have a next id");
      fail(fwd, ObjectiveError.BADPARAMS);
    }

    OLTPipelineGroup next = getGroupForNextObjective(fwd.nextId());

    if (next == null) {
      log.error("Group for forwarding objective missing: {}", fwd);
      fail(fwd, ObjectiveError.GROUPMISSING);
    }

    Group group = groupService.getGroup(deviceId, next.key());
    TrafficTreatment treatment = buildTreatment(Instructions.createGroup(group.id()));

    FlowRule rule =
        DefaultFlowRule.builder()
            .forDevice(deviceId)
            .forTable(0)
            .fromApp(fwd.appId())
            .makePermanent()
            .withPriority(fwd.priority())
            .withSelector(fwd.selector())
            .withTreatment(treatment)
            .build();

    FlowRuleOperations.Builder builder = FlowRuleOperations.builder();
    switch (fwd.op()) {
      case ADD:
        builder.add(rule);
        break;
      case REMOVE:
        builder.remove(rule);
        break;
      case ADD_TO_EXISTING:
      case REMOVE_FROM_EXISTING:
        break;
      default:
        log.warn("Unknown forwarding operation: {}", fwd.op());
    }

    applyFlowRules(builder, fwd);
  }
  @Override
  // Dell switches need ETH_DST based match condition in all IP table entries.
  // So this method overrides the default spring-open behavior and adds
  // ETH_DST match condition while pushing IP table flow rules
  protected Collection<FlowRule> processSpecific(ForwardingObjective fwd) {
    log.debug("Processing specific");
    TrafficSelector selector = fwd.selector();
    EthTypeCriterion ethType = (EthTypeCriterion) selector.getCriterion(Criterion.Type.ETH_TYPE);
    if ((ethType == null)
        || ((((short) ethType.ethType()) != Ethernet.TYPE_IPV4)
            && (((short) ethType.ethType()) != Ethernet.MPLS_UNICAST))) {
      log.debug("processSpecific: Unsupported " + "forwarding objective criteraia");
      fail(fwd, ObjectiveError.UNSUPPORTED);
      return Collections.emptySet();
    }

    TrafficSelector.Builder filteredSelectorBuilder = DefaultTrafficSelector.builder();
    int forTableId = -1;
    if (((short) ethType.ethType()) == Ethernet.TYPE_IPV4) {
      if (deviceTMac == null) {
        log.debug(
            "processSpecific: ETH_DST filtering "
                + "objective is not set which is required "
                + "before sending a IPv4 forwarding objective");
        // TODO: Map the error to more appropriate error code.
        fail(fwd, ObjectiveError.DEVICEMISSING);
        return Collections.emptySet();
      }
      filteredSelectorBuilder =
          filteredSelectorBuilder
              .matchEthType(Ethernet.TYPE_IPV4)
              .matchEthDst(deviceTMac)
              .matchIPDst(((IPCriterion) selector.getCriterion(Criterion.Type.IPV4_DST)).ip());
      forTableId = ipv4UnicastTableId;
      log.debug("processing IPv4 specific forwarding objective");
    } else {
      filteredSelectorBuilder =
          filteredSelectorBuilder
              .matchEthType(Ethernet.MPLS_UNICAST)
              .matchMplsLabel(
                  ((MplsCriterion) selector.getCriterion(Criterion.Type.MPLS_LABEL)).label());
      // TODO: Add Match for BoS
      // if (selector.getCriterion(Criterion.Type.MPLS_BOS) != null) {
      // }
      forTableId = mplsTableId;
      log.debug("processing MPLS specific forwarding objective");
    }

    TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
    if (fwd.treatment() != null) {
      for (Instruction i : fwd.treatment().allInstructions()) {
        treatmentBuilder.add(i);
      }
    }

    if (fwd.nextId() != null) {
      NextGroup next = flowObjectiveStore.getNextGroup(fwd.nextId());

      if (next != null) {
        GroupKey key = appKryo.deserialize(next.data());

        Group group = groupService.getGroup(deviceId, key);

        if (group == null) {
          log.warn("The group left!");
          fail(fwd, ObjectiveError.GROUPMISSING);
          return Collections.emptySet();
        }
        treatmentBuilder.group(group.id());
        log.debug("Adding OUTGROUP action");
      } else {
        log.warn("processSpecific: No associated next objective object");
        fail(fwd, ObjectiveError.GROUPMISSING);
        return Collections.emptySet();
      }
    }

    TrafficSelector filteredSelector = filteredSelectorBuilder.build();
    TrafficTreatment treatment = treatmentBuilder.transition(aclTableId).build();

    FlowRule.Builder ruleBuilder =
        DefaultFlowRule.builder()
            .fromApp(fwd.appId())
            .withPriority(fwd.priority())
            .forDevice(deviceId)
            .withSelector(filteredSelector)
            .withTreatment(treatment);

    if (fwd.permanent()) {
      ruleBuilder.makePermanent();
    } else {
      ruleBuilder.makeTemporary(fwd.timeout());
    }

    ruleBuilder.forTable(forTableId);
    return Collections.singletonList(ruleBuilder.build());
  }