have URl want to store json data to database automatically
site provide this code but use Java
HttpResponse response = Unirest.get("https://xproject.restdb.io/rest/data")
.header("x-apikey", "42ba8a6dc7532aa8319a58310281665e394e4")
.header("cache-control", "no-cache")
.asString();
This Example of json
model called speed contain speed & id
need save gps_speed_kph = speed & id_watch ==_id
Firstly, you have to specify the db column data type as hash in your model as described here.
Then you have to save your json as hash in your db (json to hash ):
require 'json'
value = '{"val":"test","val1":"test1","val2":"test2"}'
myhash = JSON.parse(value)
Model.create(hash_column_name: myhash)
and for converting you can do this (hash to json):
#myhash = Model.find(1).hash_column_name
json_data = #myhash.to_json
You can use JSONB column. This may help you to update the single are the group of data based on the key in the column.
Ref:
1) http://edgeguides.rubyonrails.org/active_record_postgresql.html#json-and-jsonb
2) https://nandovieira.com/using-postgresql-and-jsonb-with-ruby-on-rails
Related
In my setup using QAF Gerkin, I have an 80+ data column in the test data file which is very difficult to pass all the columns in steps using "<data_column>". I would like to retrieve all the column data directly in my StepDef according to data-driven iteration. I have tried using getBundle().getString("column_name"), but it is not working.
Eg:
Feature File:
Scenario outline: UI-34_Customer Creation
And I request api "get.sample.call"
And I assert api response status is "200"
And Test Data Retrive
Examples: {"datafile": "data/scenarios/1622630669181.csv", "filter": '(_status==true) && (_id.equalsIgnoreCase("UI-34"))'}
StepDef:
QAFTestStep(description="Test Data Retrive")/**/
public void testDataRetrive(){
System.out.println("============>>>>>>>==========");
System.out.println(getBundle().getString("customer_name"));
System.out.println("============<<<<<<<>>>>>>>==========");
}
Note: I'm able to retrive the data, if I mention the column name directly in Step.
Your step need to accept argument and value need to passed when called. In order to pass record/entry from data-provider you can use args[0] reference as value.
Refer example below:
#QAFTestStep(description="Test Data Retrive {testdata}")
public void testDataRetrive(Map<String, Object> data){
System.out.println("============>>>>>>>==========");
System.out.println(data.get("customer_name"));
System.out.println("============<<<<<<<>>>>>>>==========");
}
Scenario outline: UI-34_Customer Creation
And I request api "get.sample.call"
And I assert api response status is "200"
And Test Data Retrive "${args[0]}"
Examples: {"datafile": "data/scenarios/1622630669181.csv", "filter": '(_status==true) && (_id.equalsIgnoreCase("UI-34"))'}
Refer answer to similar question.
I have created a Dictionary with some values. I want to create JSON string of that dictionary object.
I am using String(data: data, encoding: .utf8)! to create json string but every time i run this code i am getting json string in diffrent sequence and order of same data.
import Foundation
import CommonCrypto
var object = ["emp1":["name":"neeraj","age":"14","degree":"Btech"],
"emp2":["name":"ajay","age":"24","degree":"Mca"],
"emp3":["name":"vijay","age":"34","degree":"Bca"],
"emp4":["name":"raju","age":"44","degree":"Mtech"]]
if let data = try? JSONSerialization.data(withJSONObject: object, options: []){
print(String(data: data, encoding: .utf8)!)
}
First time result:
{"emp2":{"age":"24","degree":"Mca","name":"ajay"},"emp4":{"age":"44","name":"raju","degree":"Mtech"},"emp3":{"degree":"Bca","name":"vijay","age":"34"},"emp1":{"degree":"Btech","name":"neeraj","age":"14"}}
Second time result:
{"emp1":{"age":"14","degree":"Btech","name":"neeraj"},"emp4":{"name":"raju","degree":"Mtech","age":"44"},"emp3":{"name":"vijay","age":"34","degree":"Bca"},"emp2":{"name":"ajay","age":"24","degree":"Mca"}}
I want same result for every time.
I need same order to create md5 checksum to compare with recieved checksome of data.
I am getting a response from web service
for e.g
{
"payload":{
"object1":["name":"neeraj"],
"object2":["name":"ajay"]
},
"hash":"<hash of payload using md5>"
}
i have to create an md5 hash at my side and need to verify with hash i recieved.
but when i create JSON String i got different order and my hash doesn't match with recieved hash.
Please help
Don't use MD5 it's broken.
Create your dictionary from the JSON parse and then instantiate objects from that dict.
Hash the objects with a sensible digest such as Keccak, SHA-2, SHA-3 or Blake2.
I'm new to ruby on rails, and I'm developing an application that will have very sensitive data (api keys from other websites) and I need to store it encrypted in a db but without knowing them at any time.
Let me explain myself:
The form asks the user for his api keys
Encrypt them
Store it in the db
The main question is, how do I encrypt them in such a way that I can use them later (still without knowing them)?
Sorry if the question is silly, but I can't find a way to do it, and thanks.
I've used attr_encrypted for this. Works great.
class User
attr_encrypted :ssn, key: 'This is a key that is 256 bits!!'
end
You then work with ssn as if it were a plain field
user = User.find(1)
puts user.ssn
but it's encrypted at rest (in the database) and can't be retrieved without the key.
def encrypt text
text = text.to_s unless text.is_a? String
len = ActiveSupport::MessageEncryptor.key_len
salt = SecureRandom.hex len
key = ActiveSupport::KeyGenerator.new(Rails.application.secrets.secret_key_base).generate_key salt, len
crypt = ActiveSupport::MessageEncryptor.new key
encrypted_data = crypt.encrypt_and_sign text
"#{salt}$$#{encrypted_data}"
end
def decrypt text
salt, data = text.split "$$"
len = ActiveSupport::MessageEncryptor.key_len
key = ActiveSupport::KeyGenerator.new(Rails.application.secrets.secret_key_base).generate_key salt, len
crypt = ActiveSupport::MessageEncryptor.new key
crypt.decrypt_and_verify data
end
Pass the key to encrypt method and store the returned encrypted value in DB.
Then to decrypt pass the encrypted key to the decrypt method.
This is assuming your Secret Key Base is in Rails.application.secrets.secret_key_base
The original source for the answer is here
Say I have copied the string for a cookie from a browser request.
_some_session=RXF6SVF5RHdV...
I want to open the rails console and paste something like
> session[RXF6SVF5RHdV...]
To retrieve the decrypted data from the session. If this is possible, how do I do it?
Yes it is possible, here is more detailed way, open your rails console to try this:
content = 'BAh7CEkiD3Nlc3Npb25faWQGOgZFRkkiJTgwZGFiNzhiYWZmYTc3NjU1ZmVmMGUxM2EzYmEyMDhhBjsAVEkiFGdpdGh1Yl91c2VybmFtZQY7AEZJIhJuZWVyYWpkb3RuYW1lBjsARkkiEF9jc3JmX3Rva2VuBjsARkkiMU1KTCs2dXVnRFo2R2NTdG5Kb3E2dm5BclZYRGJGbjJ1TXZEU0swamxyWU09BjsARg%3D%3D--b5bcce534ceab56616d4a215246e9eb1fc9984a4'
assuming content is your session cookie,
When the content is written to cookie then it is escaped. So first we need to unescape it.
> unescaped_content = URI.unescape(content)
=> "BAh7CEkiD3Nlc3Npb25faWQGOgZFRkkiJTgwZGFiNzhiYWZmYTc3NjU1ZmVmMGUxM2EzYmEyMDhhBjsAVEkiFGdpdGh1Yl91c2VybmFtZQY7AEZJIhJuZWVyYWpkb3RuYW1lBjsARkkiEF9jc3JmX3Rva2VuBjsARkkiMU1KTCs2dXVnRFo2R2NTdG5Kb3E2dm5BclZYRGJGbjJ1TXZEU0swamxyWU09BjsARg==--b5bcce534ceab56616d4a215246e9eb1fc9984a4"
Notice that towards the end unescaped_content has -- . That is a separation marker. The value before -- is the real payload. The value after -- is digest of data.
> data, digest = unescaped_content.split('--')
=> ["BAh7CEkiD3Nlc3Npb25faWQGOgZFRkkiJTgwZGFiNzhiYWZmYTc3NjU1ZmVmMGUxM2EzYmEyMDhhBj VEkiFGdpdGh1Yl91c2VybmFtZQY7AEZJIhJuZWVyYWpkb3RuYW1lBjsARkkiEF9jc3JmX3Rva2VuBjsARkkiMU1KTCs2dXVnRFo2R
2NTdG5Kb3E2dm5BclZYRGJ
GbjJ1TXZEU0swamxyWU09BjsARg==", "b5bcce534ceab56616d4a215246e9eb1fc9984a4"]
The data is Base64 encoded. So let’s unecode it.
> Marshal.load(::Base64.decode64(data))
=> {"session_id"=>"80dab78baffa77655fef0e13a3ba208a",
"github_username"=>"manoj910",
"_csrf_token"=>"MJL+6uugDZ6GcStnJoq6vnArVXDbFn2uMvDSK0jlrYM="}
So we are able to get the data that is stored in cookie.
Here is an answer that works for non-cookie-based sessions too. I.e. normally all that you would save in the cookie is the session ID. Now given the session ID you can lookup the session data independently from the used session store (file, cache, ActiveRecord) like this:
def lookup_session_data(session_id)
session_store = Rails.application.config.session_store.new nil, {}
_id, data = session_store.find_session({}, Rack::Session::SessionId.new(session_id))
data if data.present?
end
session_id = "..."
lookup_session_data session_id
I'm accessing the Google places API using HTTParty. Here's my code.
query = GOOGLE_API["search"].merge(:location => latlng.join(","))
response = HTTParty.get(GOOGLE_API["search"]["url"], :query => query)
#businessInfo = response
#business info contains a string of data from Google as expected, however, when I try to acccess the items using #businessInfo.index(0).item like I would with data from my database, I get nil.
This is a sample of what is contained in the variable -- {"html_attributions"=>[], "results"=>[{"geometry"=>{"location"=>{"lat"=>33.762835, "lng"=>-84.392724}}, "icon"=>"http://maps.gstatic.com/mapfiles/place_api/icons/art_gallery-71.png", "id"=>"c551a5fdc78c273e6f498aa920733037199ebe01", "name"=>"World of Coca-Cola", "reference"=>"CnRoAAAAvpKSnn971Ur5ABYStk-EJfMvyFFFlBtd9LzwRT4H-PF50vS0CQtDCGkoW0QqKLHwFHV7Qmj32bgg-KjthkVENsBpGPxNAq_vcg4do-TQyi97y6mKxf3qUgoGxzGHePEAcqg15aATTl6Xdsq7Pl2b6hIQpzVIr4KO4ZDSx4tIqcH-ARoUPn-9yBSLi35lBM7gFm2KTPGREa0", "types"=>["art_gallery", "store", "establishment"], "vicinity"=>"Baker Street Northwest, Atlanta"}, {"geometry"=>{"location"=>{"lat"=>33.759925, "lng"=>-84.387158}}, "icon"=>"http://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png", "id"=>"32815dbf0963cb55dee871b96cc5100335f40400", "name"=>"Hard Rock Cafe Atlanta", "reference"=>"CnRtAAAApKIX3M3emqAzdsN3f0ntsi-M-
My question is, What syntax do I use to access the items and values so that I can work with them.
Thanks.
Your response object is an hash so you can access your response content in the following way:
puts response["results"]