добавить несколько JSON-ответ в HTML-таблицу, используя рельсы - PullRequest
0 голосов
/ 07 января 2019

Я работаю в приложении веб-служб. Я получаю ответ ниже и сохраняю ответ в результате в контроллере. Я могу показать это в виде таблицы, такой как Код состояния, Параметры и ответ. Я выполняю с несколькими устройствами и пытаюсь для отображения ответа в UI. Проблема только в последнем выполнении Mac. Отображается ответ json. Ниже приведены результаты, отображаемые в UI. Получение двух адресов MAC, но с одинаковыми значениями в параметре_имя, коде состояния, сообщении, значении. Мне нужно отобразить ответ json для каждого выполнения устройства,

Mac Address Parameter Name  Status Code Message  Value
5C:E3:0E      Test           200            Success  72p3434 ////same value is displaying             
10:56:11      Test            200           Success  72p3434 

для mac 5c: E3: 0E с другими значениями, но с отображением значений выполнения lat mac (10:56:11). Когда я ставлю предупреждение (результат ["ответ"]. Статус), которое показывает только один (200) статус, если я запускаю несколько устройств.

Спасибо, Радж

 Json Response
   "{\"statusCode\":200,\"parameters\": 
 [{\"name\":\"Device.Description\",\"value\":\"Gateway 
Device\",\"dataType\":0,\"parameterCount\":1,\"message\":\"Success\"}]}"

     Controller
    params[:mac].each do |mac|

     //web service call for getting description for multiple devices
    end
        result_hash["response"] = {"status": response.code, 
"parameter_name": model.to_s, "body": response.body, "accesstoken": 
access_token, "response_time": response_time.to_s}
  respond_to do |format|
format.json { render :json => result }
end


 JS File

if (result["response"].status == "200") {

    var obj = JSON.parse(result["response"].body);
    var pretty = JSON.stringify(obj, undefined, 4);
    for (var i = 0; i < mac.length; i++) {

    //$('#http_response').append("Mac:"+mac+"\n\nParameter Name : 
    "+result["response"].parameter_name+"\n\nResponse Time : " + 
   result["response"].response_time + " sec\n\nResponse Body : \n" + 
   pretty);
        for (var j = 0; j < obj.parameters.length; j++) {

            tr = $('<tr/>');
            tr.append("<td>" + mac[i] + "</td>");
            tr.append("<td>" + result["response"].parameter_name + "< 
        /td>");
            tr.append("<td>" + result["response"].status + "</td>");
            tr.append("<td>" + obj.parameters[j]["message"] + "</td>")
            tr.append("<td>" + obj.parameters[j]["value"] + "</td>")
            $('#http_response').append(tr);
        }
    }




 function getParameters
  result_hash = Hash.new().merge({"response": []})
  result_hash["pa"] = false
  result_hash["tel"] = false
  result = ""

  if params[:protocol][:pa] == "true"
    result_hash["pa"] = true
    params[:mac].each do |mac|
      client = paclient.new
      @model = params[:parameter]
      if @model.to_s.first == ","
        @model = @model[1..-1]
      end
      total_params = 1
      if @model.include? (",")
        paramArray = @modle.split(/\s*,\s*/)
        p "After Conversion"
        p paramArray

        total_params = paramArray.length
      end

      puts "Total number of Params in execution = #{total_params}"

      if total_params == 1
        if mac.nil?
          flash[:notice] = "Mac cannot be nil"
          redirect_to root_path
        elsif @dataModel.nil?
          flash[:notice] = "Parameter cannot be nil"
          redirect_to root_path
        end

        response = client.get_call(mac, @model)
        redis_client = Redis.new
        access_token = redis_client["Pa:SATToken"]
        response_time = client.response_time

        # response_time = 
   Time.at(client.response_time).utc.strftime("%M:%S.%L")

        p "RESPONSE_TIME = #{response_time}"

        p "Encoding = #{response.body.encoding}"

        response.body.force_encoding("ISO-8859-1").encode("UTF-8")

        p response.body

        if access_token.nil?
          sat_client = SatClient.new
          response = sat_client.get_sat_token
          body = JSON.parse(response.body)
          if response.code == "200"
            access_token = body["access_token"]
            p "Storing Token in Redis"
            redis_client = Redis.new
            redis_client["Pa:SATToken"] = access_token
            return access_token
          else
            p "SAT endpoint returned #{response.code}"
            p "#{response.body}"
            raise "Retrieving SAT Token call failed"
          end
        end
        result_hash["response"] = {"status": response.code, "parameter_name": 
     @model.to_s, "body": response.body, "accesstoken": access_token, 
   "response_time": response_time.to_s}
      else
        result_hash["response"] = {"status": "520", "body": ""}
      end
    end
  elsif params[:protocol][:pil] == "true"
    result_hash["pil"] = true
    # cima_client=CimaClient.new
    #get CIMA token

    numberOfOids = 1

    @oid = params[:oid]
    #mac = params[:mac]
    params[:mac].each do |snmpmac|
      Rails.logger.debug("SNMP MAC: #{snmpmac.inspect}")

      if @oid.to_s.first == ","
        @oid = @oid[1..-1]
        oidArray = @oid.split(/\s*,\s*/)

        numberOfOids = oidArray.length

        puts "OID ARRAY LENGTH :- #{numberOfOids}"
      end

      puts "Before Initializing"
      snmp4jclient = Snmp4jClient.new

      puts "MacAddress is " + snmpmac

      # Get IP address for the device from the Devices table owned by the user.
      @user = User.find_by(name: session[:name])
      id = @user.id.to_s
      @device = device.find_by(User_id: id, est_mac_address: snmpmac)
      # @device = device.where("User_id IS #{id} AND est_mac_address IS \"# 
    {mac}\"")
      plarform_id = @device.platform_id.to_s

      if plarform_id == "1"
        ipAddress = @device.estb_ip
      elsif plarform_id == "2"
        ipAddress = @device.cm_ip
      end

      #          Get value using XRAY SNMP

      puts "Ipaddress = " + ipAddress
      response = snmp4jclient.make_SNMP_curl_req(ipAddress, @oid)

      puts "Response is #{response}"
      response_time = snmp4jclient.response_time
      # response_time = Time.at(client.response_time).utc.strftime("%M:%S.%L")
      p "RESPONSE_TIME = #{response_time}"

      if response != ""
        if valid_json?(response)
          snmp_output = JSON.parse(response)["response"]

          # snmp_output = format_response_SNMP(snmp_output)

          if response.include?("No Such Object available") || response.include? 
     ("Error in executing snmp walk") || response.include?("noSuchInstance") || 
    response.include?("physical.device.timeout")
            result_hash["response"] = {"status": "400", "body": snmp_output, 
    "response_time": response_time.to_s, "oid": @oid}
          else
            result_hash["response"] = {"status": "200", "body": snmp_output, 
"response_time": response_time.to_s, "oid": @oid}
          end
        else
          result_hash["response"] = {"status": "404", "body": response, 
 "response_time": response_time.to_s, "oid": @oid}
        end
      else
        result_hash["response"] = {"status": "404", "body": "No Response from Server", "oid": @oid}
      end
    end
   =begin
        if (!response.include?  || )
          result_hash["response"]={"status": "200", "body": 
  JSON.parse(response)["response"]}
        else
          result_hash["response"]={"status": "400", "body": 
 JSON.parse(response)["response"]}
        end
   end

  p result = JSON.generate(result_hash)
  respond_to do |format|
    format.json { render :json => result }
  end
rescue Exception => e
  # redirect_to root_path
  result_hash["response"] = {"status": "ERROR", "body": e.message, "response_time": "0.00"}
  result = JSON.generate(result_hash)

  respond_to do |format|
    format.json { render :json => result }
  end
end
end

1 Ответ

0 голосов
/ 07 января 2019

Похоже, здесь что-то не так с вашим кодом:

result_hash["response"] = {"status": response.code, 
"parameter_name": model.to_s, "body": response.body, "accesstoken": 
access_token, "response_time": response_time.to_s}
respond_to do |format|
format.json { render :json => result }

Вы устанавливаете result_hash и рендеринг result. И вы присваиваете result_hash["response"] с помощью = Я думаю, что вы хотите <<, который будет толкать данные в массив. Дайте мне знать, если вышеупомянутые решения не работают

Обновление:

result_hash["pa"] = false
result_hash["tel"] = false
result_hash["response"] = []
result = ""

и замените все строки, говорящие result_hash["response"] = на result_hash["response"] <<

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...