Headers are not accepting in wrk.format - lua

I am trying to post data to API. I am building request every time. and I am adding headers to wrk.format() method. The headers are not accepting event though headers type is string.
headers = {}
s = {}
request = function()
headers["Authorization"] = "key"
for name, value in pairs(headers) do
s[1] = string.format("%s: %s", name, value)
end
print(s[1])
print(type(s[1])
return wrk.format("POST", "/api/", s[1] ,data)
end
throwing error :
PANIC: unprotected error in call to Lua API ([string "wrk"]:0: attempt to index field 'headers' (a string value))
Can anyone help me with this?
Thanks in advance.

You need to pass the entire dictionary to the format function
return wrk.format("POST", "/api/", headers ,data)
in case of mine the headers look like:
headers = {}
headers["Content-Type"] = "application/json"

Related

Retrieving "$ref" field in swagger.json

I am trying to use the swagger parser to parse and retrieve information in the "swagger.json" (io.swagger.parser.SwaggerParser;)
Below is an excerpt of the "swagger.json".
I am trying to retrieve "$ref" : "#/definitions/abc".
"responses" : {
"200" : {
"description" : "abc",
"schema" : {
"$ref" : "#/definitions/abc"
}
},
This is the code to parse it.
SwaggerParser sparse = new SwaggerParser();
Swagger swagger = sparse.read("swagger.json");
// This next line is what I am having a problem with.
swagger.getPath("/endpointurl").getGet().getResponses().get("200").getSchema();
At this point, the ".getSchema()" in the above line has only "getType()" in it I can call. It doesn't have "get$ref()". This is because ".getSchema()" returns a "Property" (io.swagger.models.properties.Property). It doesn't have "get$ref()".
get$ref() is available in "RefProperty" (io.swagger.models.properties.RefProperty)
But ".getSchema()" doesn't return a "RefProperty".
Typecast the result of ".getSchema()" to a "RefProperty" also doesn't work. It ends up in this error.
java.lang.ClassCastException: io.swagger.models.properties.ArrayProperty cannot be cast to io.swagger.models.properties.RefProperty
Has anyone tried parsing a "swagger.json" and was able to retrieve the "$ref": line under "schema" in the "response" block?
Any idea how might I be able to do that?
I figured out a way to do that. Maybe not the best way to do it, but it retrieves the information in "#ref".
Object obj = xxxxx.getSchema(); // xxxxx is whatever your code that gives you ".getSchema()". Mine is in a map and I don't want to distract people.
ArrayProperty arrProp = new ArrayProperty();
arrProp = (ArrayProperty)obj; // .getSchema() returns an ArrayProperty
RefProperty refProperty = (RefProperty) arrProp.getItems(); // .getItems() will return the RefProperty type you need to call ".get$ref()".
String refStr = refProperty.get$ref(); // Voila, there's your content in "#ref".
String simpleRefStr = refProperty.getSimpleRef();
I had to do a few type castings. If you have a more elegant way of doing this, please post here.

PHPExcel str_replace

i want to convert my excel hyperlink's path to open links with PHPExcel.
$links = $objPHPExcel->getActiveSheet()->getHyperlinkCollection();
This method will return an array of hyperlink objects, indexed by cell address; and you could then use array_filter() with an appropriate callback and the ARRAY_FILTER_USE_KEY flag set to extract those within a specific range.
my var_dump($links); output :
But i dont know how to loop the array of objects with array_filter() function..
I try :
$test = str_replace($links, "file", "mnt");
var_dump($test);
and i got the error above.. Any ideas please ?
The collection is an array of objects, indexed by cell address; and the PHPExcel_Cell_Hyperlink object has a set of documented methods for accessing and setting its data:
foreach($links as $cellAddress => $link) {
// get the URL from the PHPExcel_Cell_Hyperlink object
$url = $link->getUrl();
// change the URL however you want here
$url = str_replace($url, "file", "mnt");
// Set the new value for the link
$link->setUrl($url);
}
If you want to modify just those URLs for cells in column N, then you can wrap them in an if test:
foreach($links as $cellAddress => $link) {
// Test for column N
sscanf($cellAddress, '%[A-Z]%d', $column, $row);
if ($column == 'N') {
// get the URL from the PHPExcel_Cell_Hyperlink object
$url = $link->getUrl();
// change the URL however you want here
$url = str_replace($url, "file", "mnt");
// Set the new value for the link
$link->setUrl($url);
}
}

Convert React.FormEvent to BodyInit using Fable-Elmish

I am trying to upload a file using Fable-Elmish and the React Helpers. However, I can't work out how to convert the form event when a file is selected into something that I can send off to the server using Fetch. This is the view:
R.input [
ClassName "input-control"
Type "file"
OnChange (fun x -> FileUploaded x.target |> dispatch )
] []
The corresponding part of my update function:
| FileUploaded file ->
model, Cmd.ofPromise postCsv file FetchSuccess FetchFailure
And the function to call the api with fetch:
let postData input =
let formData = FormData.Create()
formData.append("file.csv", input?files)
let defaultProps =
[ RequestProperties.Method HttpMethod.POST
; RequestProperties.Body (formData |> unbox)]
promise {
return! Fable.PowerPack.Fetch.fetch ("/api/data") defaultProps
}
How can I can convert the React.FormEvent into the BodyInit that fetch needs?
Your going to need to create a new FormData object and append the file to it.
let formData = FormData.createNew
formData.append("file", file.[0])
Then change your call to postRecord to pass formData instead of file. You need fetch to encode it, but you are just passing the raw array of files.
At least that is my understanding from the fetch example on uploading a file. Also, post record looks wrong to me, is there just a "post" method you could use? postRecord implies it is expecting a record type.
I think Fetch.postRecord is your problem, it sets Content-Type header to application/json, when it should be multipart/form-data.
You need to use raw fetch API, instead of powerpack wrapper, something like this.
Upon testing your code, checking ev.target?value revealed that the event just grabs the name of the selected file. postRecord appears to be used for sending json to an endpoint. You are going to want to port: https://medium.com/ecmastack/uploading-files-with-react-js-and-node-js-e7e6b707f4ef , to what you want to do.
It turns out I wasn't using the FileList API properly. Here's the working solution for the post method:
let postData input =
let formData = FormData.Create()
formData.append("file.csv", input?files?item(0))
let defaultProps =
[ RequestProperties.Method HttpMethod.POST
;RequestProperties.Headers [unbox EncType "multipart/form-data"]
; RequestProperties.Body (formData |> unbox)]
promise {
return! Fable.PowerPack.Fetch.fetch ("/api/data") defaultProps
}

Spock Testing a POST Service in Grails

EDIT 2: Figured out how to pass an integer, however my now my test is failing because the value coming back is empty but the render is the correct value on the web page.
EDIT: I've figured out how to pass values by POST using the request.method, however i now can't figure out how to pass an int into the controller using request, as each addParameter expects a string.
I have a convert application in grails, where both the binary and hex service take a parameter via post before converting it to either binary or hex and returning the result. I'm now writing some Spock tests to test each service however i can't seem to figure out how to test the service if the parameter is required to be sent via POST rather than GET.
Binary Convert Service:
def binary() {
if (request.method == 'POST') {
if (session.user) {
Integer number = params.getInt('number')
String binary = Integer.toBinaryString(number)
def r = new Results()
r.customerID = session["id"]
r.username = session["username"]
r.ConvertService = "binary"
r.number = number
r.result = binary
r.date = new Date()
r.time = new Timestamp(System.currentTimeMillis())
if(r.save()) {
render binary
} else {
render r.getErrors()
}
} else {
redirect(controller: 'main')
}
} else {
response.sendError(405)
}
}
Spock test:
void "Binary Service should return 1100"() {
given:
def convert = new ConvertController()
when:
def result = convert.binary(12)
then:
result == 1100
}
This is what my test returns right now:
groovy.lang.MissingMethodException: No signature of method: eadassignment.ConvertController.binary() is applicable for argument types: (java.lang.Integer) values: [12]
Possible solutions: binary(), any(), <init>(), index(), every(), find()
at org.codehaus.groovy.grails.plugins.web.api.ControllerTagLibraryApi.methodMissing(ControllerTagLibraryApi.java:97)
at eadassignment.ConvertControllerSpec.Binary Service should return 1100(ConvertControllerSpec.groovy:22)
Figured out all my problems. Last one was because the function checked if a valid user existed which the test was failing for obvious reasons.

JSON made with .to_json (of a collection) in Rails model not readable jquery

I fetched the results of a query in the model. Next i right away added a .to_json and assumed I will get a correct JSON object. But JQuery was not able to parse the json
def self.get_all_specials(year)
data_array=AttributeCalendarAnnual.find(:all, :conditions=>["created_at between ? and ?",Date.civil(Date.today.year), Date.civil(Date.today.next_year.year)], :order=>["created_at asc"])
return data_array.to_json
end
But the result I get is not a valid JSON it seems.
EDIT
The output :
[{"created_at":"2012-01-17T17:38:27Z","id":1,"in_market_end_date":"2012-01-31T23:59:59Z","in_market_start_date":"2012-01-18T00:00:00Z","initiative_id":1,"is_mail_count_selected":true,"is_mailer_selected":true,"is_market_selected":true,"is_offer_selected":true,"mail_count":1,"mailer_start_date":"2012-01-25T00:00:00Z","offer_selection_end_date":"2012-01-12T23:59:59Z","offer_selection_start_date":"2012-01-09T00:00:00Z","updated_at":"2012-01-17T17:38:27Z"},{"created_at":"2012-01-17T20:21:37Z","id":2,"in_market_end_date":"2012-01-28T23:59:59Z","in_market_start_date":"2012-01-24T00:00:00Z","initiative_id":3,"is_mail_count_selected":true,"is_mailer_selected":true,"is_market_selected":true,"is_offer_selected":true,"mail_count":5,"mailer_start_date":"2012-01-30T00:00:00Z","offer_selection_end_date":"2012-01-21T23:59:59Z","offer_selection_start_date":"2012-01-09T00:00:00Z","updated_at":"2012-01-17T20:21:37Z"}]
if you are simply outputting the escaped object to your page and hoping JS will parse it this will not work because it will be interpreted as a string. Instead try feeding the string into a function like this:
function parseJSON(txt, escape) {
if (escape === true) {
txt = unescape(txt);
}
return new Function("return " + txt)();
}
var result = parseJSON(someString);

Resources