<commit_before>package com.cisco.trex;

import com.cisco.trex.stateless.TRexCommand;
import com.cisco.trex.stateless.TRexTransport;
import com.cisco.trex.stateless.exception.TRexConnectionException;
import com.cisco.trex.stateless.model.L2Configuration;
import com.cisco.trex.stateless.model.Port;
import com.cisco.trex.stateless.model.PortStatus;
import com.cisco.trex.stateless.model.RPCResponse;
import com.cisco.trex.stateless.model.StubResult;
import com.cisco.trex.stateless.model.SystemInfo;
import com.cisco.trex.stateless.model.TRexClientResult;
import com.cisco.trex.stateless.model.capture.CaptureInfo;
import com.cisco.trex.stateless.model.capture.CaptureMonitor;
import com.cisco.trex.stateless.model.capture.CaptureMonitorStop;
import com.cisco.trex.stateless.model.capture.CapturedPackets;
import com.cisco.trex.stateless.model.stats.ExtendedPortStatistics;
import com.cisco.trex.stateless.model.stats.PortStatistics;
import com.cisco.trex.stateless.model.stats.XstatsNames;
import com.cisco.trex.stateless.util.DoubleAsIntDeserializer;
import com.cisco.trex.util.Constants;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** Base class for stateful and stateless classes */
public abstract class ClientBase {

  private static final String CAPTURE_ID = "capture_id";
  private static final String CAPTURE = "capture";
  private static final String COMMAND = "command";
  protected static final String API_H = "api_h";
  private static final String RESULT = "result";
  protected static final String PORT_ID = "port_id";
  protected static final Logger LOGGER = LoggerFactory.getLogger(ClientBase.class);
  protected static final Gson GSON = buildGson();
  protected String host;
  protected String port;
  protected String userName = "";
  protected final Map<Integer, String> portHandlers = new HashMap<>();
  protected final Set<String> supportedCmds = new HashSet<>();
  protected final Random randomizer = new Random();
  protected TRexTransport transport;
  protected String apiH;
  protected String masterHandler;

  private static Gson buildGson() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(
        new TypeToken<Map<String, Object>>() {}.getType(), new DoubleAsIntDeserializer());
    return gsonBuilder.create();
  }

  private String buildRequest(String methodName, Map<String, Object> payload) {
    if (payload == null) {
      payload = new HashMap<>();
    }
    Map<String, Object> parameters = new HashMap<>();
    parameters.put("id", "aggogxls");
    parameters.put("jsonrpc", Constants.JSON_RPC_VERSION);
    parameters.put("method", methodName);
    payload.put(API_H, apiH);
    parameters.put("params", payload);
    return GSON.toJson(parameters);
  }

  private String call(String json) {
    return this.transport.sendJson(json);
  }

  private List<TRexCommand> buildRemoveCaptureCommand(List<Integer> captureIds) {
    return captureIds
        .stream()
        .map(
            captureId -> {
              Map<String, Object> parameters = new HashMap<>();
              parameters.put(COMMAND, "remove");
              parameters.put(CAPTURE_ID, captureId);
              return buildCommand(CAPTURE, parameters);
            })
        .collect(Collectors.toList());
  }

  /**
   * Get Ports
   *
   * @return port list
   */
  public List<Port> getPorts() {
    LOGGER.info("Getting ports list.");
    List<Port> ports = getSystemInfo().getPorts();
    ports
        .stream()
        .forEach(
            port -> {
              TRexClientResult<PortStatus> result = getPortStatus(port.getIndex());
              if (result.isFailed()) {
                return;
              }
              PortStatus status = result.get();
              L2Configuration l2config =
                  status.getAttr().getLayerConiguration().getL2Configuration();
              port.hw_mac = l2config.getSrc();
              port.dst_macaddr = l2config.getDst();
            });

    return ports;
  }

  /**
   * @param portIndex
   * @return Port
   */
  public Port getPortByIndex(int portIndex) {
    List<Port> ports = getPorts();
    if (ports.stream().noneMatch(p -> p.getIndex() == portIndex)) {
      LOGGER.error(
          String.format("Port with index %s was not found. Returning empty port", portIndex));
    }
    return getPorts()
        .stream()
        .filter(p -> p.getIndex() == portIndex)
        .findFirst()
        .orElse(new Port());
  }

  /**
   * call Method
   *
   * @param methodName
   * @param payload
   * @return result
   */
  public String callMethod(String methodName, Map<String, Object> payload) {
    LOGGER.info("Call {} method.", methodName);
    if (!this.supportedCmds.contains(methodName)) {
      LOGGER.error("Unsupported {} method.", methodName);
      throw new UnsupportedOperationException();
    }
    String req = this.buildRequest(methodName, payload);
    return call(req);
  }

  /**
   * call Methods
   *
   * @param commands
   * @return results
   */
  public TRexClientResult<List<RPCResponse>> callMethods(List<TRexCommand> commands) {
    TRexClientResult<List<RPCResponse>> result = new TRexClientResult<>();

    try {
      RPCResponse[] rpcResponses = transport.sendCommands(commands);
      result.set(Arrays.asList(rpcResponses));
    } catch (IOException e) {
      String msg = "Unable to send RPC Batch";
      result.setError(msg);
      LOGGER.error(msg, e);
    }
    return result;
  }

  /**
   * call method
   *
   * @param <T>
   * @param methodName
   * @param parameters
   * @param responseType
   * @return result
   */
  public <T> TRexClientResult<T> callMethod(
      String methodName, Map<String, Object> parameters, Class<T> responseType) {
    LOGGER.info("Call {} method.", methodName);
    if (!this.supportedCmds.contains(methodName)) {
      LOGGER.error("Unsupported {} method.", methodName);
      throw new UnsupportedOperationException();
    }
    TRexClientResult<T> result = new TRexClientResult<>();
    try {
      RPCResponse response = transport.sendCommand(buildCommand(methodName, parameters));
      if (!response.isFailed()) {
        T resutlObject = new ObjectMapper().readValue(response.getResult(), responseType);
        result.set(resutlObject);
      } else {
        result.setError(
            response.getError().getMessage() + " " + response.getError().getSpecificErr());
      }

      return result;
    } catch (IOException var7) {
      String errorMsg =
          "Error occurred during processing '"
              + methodName<commit_msg>trex log is too detail<commit_after>package com.cisco.trex;

import com.cisco.trex.stateless.TRexCommand;
import com.cisco.trex.stateless.TRexTransport;
import com.cisco.trex.stateless.exception.TRexConnectionException;
import com.cisco.trex.stateless.model.L2Configuration;
import com.cisco.trex.stateless.model.Port;
import com.cisco.trex.stateless.model.PortStatus;
import com.cisco.trex.stateless.model.RPCResponse;
import com.cisco.trex.stateless.model.StubResult;
import com.cisco.trex.stateless.model.SystemInfo;
import com.cisco.trex.stateless.model.TRexClientResult;
import com.cisco.trex.stateless.model.capture.CaptureInfo;
import com.cisco.trex.stateless.model.capture.CaptureMonitor;
import com.cisco.trex.stateless.model.capture.CaptureMonitorStop;
import com.cisco.trex.stateless.model.capture.CapturedPackets;
import com.cisco.trex.stateless.model.stats.ExtendedPortStatistics;
import com.cisco.trex.stateless.model.stats.PortStatistics;
import com.cisco.trex.stateless.model.stats.XstatsNames;
import com.cisco.trex.stateless.util.DoubleAsIntDeserializer;
import com.cisco.trex.util.Constants;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** Base class for stateful and stateless classes */
public abstract class ClientBase {

  private static final String CAPTURE_ID = "capture_id";
  private static final String CAPTURE = "capture";
  private static final String COMMAND = "command";
  protected static final String API_H = "api_h";
  private static final String RESULT = "result";
  protected static final String PORT_ID = "port_id";
  protected static final Logger LOGGER = LoggerFactory.getLogger(ClientBase.class);
  protected static final Gson GSON = buildGson();
  protected String host;
  protected String port;
  protected String userName = "";
  protected final Map<Integer, String> portHandlers = new HashMap<>();
  protected final Set<String> supportedCmds = new HashSet<>();
  protected final Random randomizer = new Random();
  protected TRexTransport transport;
  protected String apiH;
  protected String masterHandler;

  private static Gson buildGson() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(
        new TypeToken<Map<String, Object>>() {}.getType(), new DoubleAsIntDeserializer());
    return gsonBuilder.create();
  }

  private String buildRequest(String methodName, Map<String, Object> payload) {
    if (payload == null) {
      payload = new HashMap<>();
    }
    Map<String, Object> parameters = new HashMap<>();
    parameters.put("id", "aggogxls");
    parameters.put("jsonrpc", Constants.JSON_RPC_VERSION);
    parameters.put("method", methodName);
    payload.put(API_H, apiH);
    parameters.put("params", payload);
    return GSON.toJson(parameters);
  }

  private String call(String json) {
    return this.transport.sendJson(json);
  }

  private List<TRexCommand> buildRemoveCaptureCommand(List<Integer> captureIds) {
    return captureIds
        .stream()
        .map(
            captureId -> {
              Map<String, Object> parameters = new HashMap<>();
              parameters.put(COMMAND, "remove");
              parameters.put(CAPTURE_ID, captureId);
              return buildCommand(CAPTURE, parameters);
            })
        .collect(Collectors.toList());
  }

  /**
   * Get Ports
   *
   * @return port list
   */
  public List<Port> getPorts() {
    LOGGER.debug("Getting ports list.");
    List<Port> ports = getSystemInfo().getPorts();
    ports
        .stream()
        .forEach(
            port -> {
              TRexClientResult<PortStatus> result = getPortStatus(port.getIndex());
              if (result.isFailed()) {
                return;
              }
              PortStatus status = result.get();
              L2Configuration l2config =
                  status.getAttr().getLayerConiguration().getL2Configuration();
              port.hw_mac = l2config.getSrc();
              port.dst_macaddr = l2config.getDst();
            });

    return ports;
  }

  /**
   * @param portIndex
   * @return Port
   */
  public Port getPortByIndex(int portIndex) {
    List<Port> ports = getPorts();
    if (ports.stream().noneMatch(p -> p.getIndex() == portIndex)) {
      LOGGER.error(
          String.format("Port with index %s was not found. Returning empty port", portIndex));
    }
    return getPorts()
        .stream()
        .filter(p -> p.getIndex() == portIndex)
        .findFirst()
        .orElse(new Port());
  }

  /**
   * call Method
   *
   * @param methodName
   * @param payload
   * @return result
   */
  public String callMethod(String methodName, Map<String, Object> payload) {
    LOGGER.debug("Call {} method.", methodName);
    if (!this.supportedCmds.contains(methodName)) {
      LOGGER.error("Unsupported {} method.", methodName);
      throw new UnsupportedOperationException();
    }
    String req = this.buildRequest(methodName, payload);
    return call(req);
  }

  /**
   * call Methods
   *
   * @param commands
   * @return results
   */
  public TRexClientResult<List<RPCResponse>> callMethods(List<TRexCommand> commands) {
    TRexClientResult<List<RPCResponse>> result = new TRexClientResult<>();

    try {
      RPCResponse[] rpcResponses = transport.sendCommands(commands);
      result.set(Arrays.asList(rpcResponses));
    } catch (IOException e) {
      String msg = "Unable to send RPC Batch";
      result.setError(msg);
      LOGGER.error(msg, e);
    }
    return result;
  }

  /**
   * call method
   *
   * @param <T>
   * @param methodName
   * @param parameters
   * @param responseType
   * @return result
   */
  public <T> TRexClientResult<T> callMethod(
      String methodName, Map<String, Object> parameters, Class<T> responseType) {
    LOGGER.debug("Call {} method.", methodName);
    if (!this.supportedCmds.contains(methodName)) {
      LOGGER.error("Unsupported {} method.", methodName);
      throw new UnsupportedOperationException();
    }
    TRexClientResult<T> result = new TRexClientResult<>();
    try {
      RPCResponse response = transport.sendCommand(buildCommand(methodName, parameters));
      if (!response.isFailed()) {
        T resutlObject = new ObjectMapper().readValue(response.getResult(), responseType);
        result.set(resutlObject);
      } else {
        result.setError(
            response.getError().getMessage() + " " + response.getError().getSpecificErr());
      }

      return result;
    } catch (IOException var7) {
      String errorMsg =
          "Error occurred during processing '"
              + methodName
{'fraction_non_alphanumeric': 0.11878989730779906, 'fraction_numerical': 0.0013877324451845685, 'mean_word_length': 3.3636088404480775, 'pattern_counts': {'":': 0, '<': 67, '<?xml version=': 0, '>': 75, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4730207', 'n_tokens_mistral': 4292, 'n_tokens_neox': 4291, 'n_words': 923}