scala.js form processing in client / access to form on scala.js client - scala.js

I want submit a form and want to show the user the process with spinner and reload the new information.
#JSExport
def addToCart(form: html.Form): Unit = {
form.onsubmit = (e: dom.Event) => {
e.preventDefault()
}
val waitSpan = span(
`class` := Waiting.glyphIconWaitClass
)
val waiting = form.getElementsByTagName("button").head.appendChild(waitSpan.render)
dom.window.alert(JSON.stringify( form.elements.namedItem("quantity") ))
Ajax.InputData
Ajax.post(form.action,withCredentials = true).map{q =>
//
}
}
I have no access to form data. Also I cannot execute an ajax call to proof the form and execute it. I have found no way. Someone has an idea?

jQuery helps. I used them now to serialize the form. But now I have no longer the ability of play forms with bindOfRequest()
val jForm = $("#"+form.id)
val serialized = jForm.serialize()
Ajax.post(s"/js/api/form/${UUID.randomUUID().toString}",withCredentials = false,timeout = 12000,data = serialized,headers = Map("X-CSRFToken"->"nocheck","Csrf-Token"->"nocheck"))
I get always:
occurrence%5B%5D=400g&quantity=1&csrfToken=c1606da9a261a7f3284518d4f1fd63eaa8bbb59e-1483472204854-1c5af366c62520883474c160
But now I don´t know what I have to do. Sorry.
def executeAddToCartForm(articleId: UUID) = silhouette.UserAwareAction.async{implicit req =>
val form = complexCartForm.bindFromRequest()
Try(form.get) match {
case Success((i,seq)) => println("article: " + i)
case _ => println(form.errors.mkString + " " + req.body.asText + " " + URLDecoder.decode(req.body.asText.get,"UTF-8"))
}
Future.successful(Ok("danke"))
}
Always get failure :( I will have a look at react.
ADDED
Sometimes I need more sleep!
Ajax.post(
url = form.action,
withCredentials = true,
timeout = 12000,
data = serialized,
headers = Map("Content-Type" -> "application/x-www-form-urlencoded")
)
with this: headers = Map("Content-Type" -> "application/x-www-form-urlencoded") I can use the bindFromRequest() as usually :)
Coffee I need more

Related

Use stored values in another scenerio : Gatling

I want to store returned values from scenerio1 to list and use the same stored values in another scenerio .
I tried to do like below . but in get scenerio this gives error id not found . I also noticed that feeder is initialized before scenerio execution itself.
Could some one please help on this .
var l: List[String] = List()
var ids = l.map(id => Map(“id” -> id)).iterator
val install = scenario(" Install")
.during(Configuration.duration) {
group("installTest") {
exec(
testChain.installApplication()
).exec(session=>{
l = session(“id”).as[String].trim :: l
print(l)
session
})
}
}
val get = scenario(“get”)
.during(Configuration.duration) {
group(“getTest”) {
feed(ids)
exec(
session=>{
print(session(“id”).as[String])
session
}
)
}
}
setUp(
warmupScenario.inject(constantConcurrentUsers(1) during(1))
.andThen(
install.inject(nothingFor(10 seconds), (rampUsers(Configuration.users) during (Configuration.ramp seconds))))
.andThen(
get.inject(nothingFor(Configuration.duration seconds), (rampUsers(Configuration.users) during (Configuration.ramp seconds))))
)
.assertions(details("installTest").successfulRequests.percent.gte(Configuration.passPercentage))
.protocols(HTTP_PROTOCOL)

Gatling print to file if KO

I have an .exec which for some values in my parameter list results in KO (value does not exists in the SUT).
I further have the need to print these values to a file so I later can remove them from the parameter list in order to not get KO`s.
I have a writer defined
val writer = {
val fos = new java.io.FileOutputStream("testresultater.txt")
new java.io.PrintWriter(fos,true)
}
and wonder how I could do this just for KOs inside the .exec resulting in KOs for some values like this:
.exec(http("request_lagDokument")
.post("/proxy/dokumenter/api/v1/SaveDokumentFil?IsDebug=true")
.headers(headers_3)
.body(ElFileBody("magnus/LagDokument.json"))
.check(status.is(expected = 200))
.check(jsonPath("$.DokumentGuid").saveAs("DokumentGuid")))
//if KO then:
.exec((s: Session) => {
writer.println(s.attributes("pnr"))
s
})
Is this possible?
You can do this by having a session function that is always executed with the conditional logic inside
.exec(session = {
if (session.isFailed) {
writer.println(s.attributes("pnr"))
}
session
})
or you can use the dsl's doIf
.doIf(session => session.isFailed) {
exec(session => {
writer.println(s.attributes("pnr"))
session
}
}

Enable branch protection rules in Github at the Organisation level

Is it possible to enable branch protection rules at the organisation level in Github so that all repositories part of that organisation inherit these rules for the applied branches. Right now its really a hassle to enable those same set of rules on a per repo basis for same set of branches.
I got it to work using a simple ruby script that makes use of the GitHub APIs :-
require "json"
require "logger"
LOGGER = Logger.new(STDOUT)
def run(cmd)
LOGGER.debug("Running: #{cmd}")
output = `#{cmd}`
raise "Error: #{$?}" unless $?.success?
output
end
def repos(page = 1, list = [])
cmd = %Q{curl -s --user "user:pwd" https://github_url/api/v3/orgs/org_name/repos?page=#{page}}
data = JSON.parse(run(cmd))
list.concat(data)
repos(page + 1, list) unless data.empty?
list
end
repos.each do |repo|
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://github_url/api/v3/repos/org_name/#{repo["name"]}/branches/master/protection")
request = Net::HTTP::Put.new(uri)
request.basic_auth("user", "pwd")
request["Accept"] = "application/vnd.github.luke-cage-preview+jso"
request.body = JSON.dump({
"required_status_checks" => {
"strict" => true,
"contexts" => [
"continuous-integration/travis-ci"
]
},
"enforce_admins" => true,
"required_pull_request_reviews" => {
"dismiss_stale_reviews" => true
},
"restrictions" => nil
})
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
end
Taken from #Ashley 's answers, updated it a bit, with a slight change to reflect current Github's API URLs and, added customization using GITHUB_ORG and GITHUB_ACCESS_TOKEN environment variables.
require "json"
require "logger"
$org = ENV["GITHUB_ORG"]
$token = ENV["GITHUB_ACCESS_TOKEN"]
LOGGER = Logger.new(STDOUT)
def run(cmd)
LOGGER.debug("Running: #{cmd}")
output = `#{cmd}`
raise "Error: #{$?}" unless $?.success?
output
end
def repos(page = 1, list = [])
cmd = %Q{curl -s -u dummy:#{$token} https://api.github.com/orgs/#{$org}/repos?page=#{page}}
data = JSON.parse(run(cmd))
list.concat(data)
repos(page + 1, list) unless data.empty?
list
end
repos.each do |repo|
p(repo["name"])
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.github.com/repos/#{$org}/#{repo["name"]}/branches/master/protection")
request = Net::HTTP::Put.new(uri)
request.basic_auth("dummy", $token)
request["Accept"] = "application/vnd.github.luke-cage-preview+jso"
request.body = JSON.dump({
"required_status_checks" => {
"strict" => true,
"contexts" => []
},
"enforce_admins" => true,
"required_pull_request_reviews" => {
"dismiss_stale_reviews" => true
},
"restrictions" => nil
})
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
p(response)
end
You should try using the Github API's update branch protection endpoint with some kind of automated process to apply branch protection rules to all new branches in your organization.
PUT /repos/:owner/:repo/branches/:branch/protection

Image capture/upload with Phonegap (cordova) for iPhone not working

I have been trying to set up an app through PhoneGap (Cordova) to take images and upload them to our server. I have gone through so many of the responses on here and tried the code in them. I can get the camera up and taking a photo, I can access the phone gallery even. But I can not get it to send the image to the server. I've tried sending the image, and even sending the base64 image stream. I can't get it to the server.
Here is the javascript on the client side:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
}
function ImageUpload() {
this.useExistingPhoto = function(e) {
this.capture(Camera.PictureSourceType.SAVEDPHOTOALBUM);
}
this.takePhoto = function(e) {
this.capture(Camera.PictureSourceType.CAMERA);
}
this.capture = function(sourceType) {
navigator.camera.getPicture(this.onCaptureSuccess, this.onCaptureFaile, {
destinationType: Camera.DestinationType.FILE_URI,
soureType: sourceType,
correctOrientation: true
});
}
this.onCaptureSuccess = function(imageURI) {
var fail, ft, options, params, win;
success = function(response) {
alert("Your photo has been uploaded!");
};
fail = function(error) {
alert("An error has occurred: Code = " + error.code + "\nMessage = "+error.message);
};
options = new FailUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "text/plain";
params = {
val1: "some value",
val2: "some other value"
};
options.params = params;
ft= new FileTransfer();
ft.upload(imageURI, 'http://style.appdev01.com/app/client-profile.php', success, faile, options);
}
this.OnCaptureFail = function(message) {
alert("Failed because: "+message);
}
};
var imageuploader = new ImageUpload();
Two buttons call imageuploader.takePhoto and .useExistingPhoto on click.
On the server side I have this php:
if(isset($_FILES['file'])) {
$target_path = "/home/style/public_html/images/client_images/app_image.jpg";
move_uploaded_file($_FILES['file']['tmp_name'], $target_path);
$insert = "INSERT INTO
`fut`
SET
`request` = '".serialize($_POST)."',
`file` = '".serialize($_FILES)."'";
$mysql->query($insert);
}
This is just to store the POST and FILE arrays to the db to make sure they came through and create the image.
But again, nothing is getting to the server. Any help would be GREATLY appreciated. I've tried so many versions of this code from so many questions here and all over the web.
define ('SITE_ROOT', realpath(dirname(__FILE__))); /* echo SITE_ROOT; to dir
move_uploaded_file($_FILES["file"]["tmp_name"],SITE_ROOT."/uploads/".$_FILES["file"]["name"]); // will move file, make sure uplaods has write permission!
That works for me on Android Simulator, not on Tablet, but let me know if you have it working, busy on the same thing.
$myarray = array( $_REQUEST);
foreach ($myarray as $key => $value) {
echo "<p>".$key."</p>";
echo "<p>".$value."</p>";
echo "<hr />";
}
That you can use to check POST / GET!
Try this is my code. It has worked for me.
Encode your URL by encodeURI method
fileKey with "file" as in your server side script $_FILES['file']
uploadFile: function(refNo){
var uri = fileUpload.fileUri;
var file = uri.substr(uri.lastIndexOf('/') + 1);
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = file;
options.mimeType="image/jpeg";
alert("name === "+uri);
options.chunkedMode = false;
var ft = new FileTransfer();
Common.ajaxLoading('show');
ft.upload(uri,encodeURI("http://172.16.1.147:80/upload/home.php") , fileUpload.uploadSuccess, fileUpload.uploadFail, options, true);
},

How to get most popular Facebook post in R

I am trying to use the following code to get posts from a page on Facebook. I get an error even though the query works when I type it in a browser. This is the error I get:
WWW-Authenticate: OAuth "Facebook Platform" "invalid_request" "Unknown path components:
Any thoughts are greatly appreciated!
# go to 'https://developers.facebook.com/tools/explorer' to get your access token
access_token <- "### token ###"
require(RCurl)
require(rjson)
cafile <- system.file("CurlSSL", "cacert.pem", package = "RCurl")
options(RCurlOptions = list(verbose = TRUE, followlocation = TRUE, timeout = 100, useragent = "R"))
# set the curl options
curl <- getCurlHandle()
options(RCurlOptions = list(capath = system.file("CurlSSL", "cacert.pem",
package = "RCurl"),
ssl.verifypeer = FALSE, verbose = TRUE, cookiejar = 'my_cookies.txt',
cookiefile = 'my_cookies.txt', followlocation = TRUE,
useragent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3'))
curlSetOpt(.opts = list(proxy = 'proxyserver:port'), curl = curl)
# Facebook json function copied from original (Romain Francois) post
facebook <- function( path = "me", access_token, options){
if( !missing(options) ){
options <- sprintf( "?%s", paste( names(options), "=", unlist(options), collapse = "&", sep = "" ) )
} else {
options <- ""
}
data <- getURL( sprintf( "https://graph.facebook.com/%s%s&access_token=%s", path, options, access_token ) )
fromJSON( data )
}
### TED FACEBOOK PAGE
# http://www.facebook.com/TED
# TED's Facebook ID 29092950651 can be found on http://graph.facebook.com/TED
ted <- list()
i<-0
next.path <- "29092950651/posts"
# download all TED posts
while(length(next.path)!=0) {
i<-i+1
ted[[i]] <- facebook( path=next.path , access_token=access_token)
next.path <- sub("https://graph.facebook.com/","",ted[[i]]$paging$'next')
}
ted[[i]] <- NULL
# parse just video links posted by TED
parse.count.ted <- function(x)
if (x$type=="link" & x$from$id=="29092950651") x$likes$count else NA
parse.link.ted <- function(x)
if (x$type=="link" & x$from$id=="29092950651") x$link else NA
ted.counts <- unlist(sapply(ted, parse.master, f=parse.count.ted))
ted.links <- unlist(sapply(ted, parse.master, f=parse.link.ted))
# see three most popular talks
ted.links[order(ted.counts,decreasing=TRUE)][1:3]
This might be a problem of how the URL is being formatted. If the options argument is not specified, the resulting URL would look like: /me/photos&access_token=.... Here, the path would be /me/photos&access_token which probably is not a valid URL component as per Facebook API.
I think the following changes to the facebook function would fix this:
require(RCurl)
require(rjson)
facebook <- function( path = "me", access_token = token, options){
if( !missing(options) ){
options <- sprintf(
"?%s&",
paste(
names(options), "=", unlist(options),
collapse = "&", sep = ""
)
)
} else {
options <- "?"
}
urlTemplate <- "https://graph.facebook.com/%s%saccess_token=%s"
data <- getURL(
sprintf(
urlTemplate,
path,
options,
access_token
)
)
fromJSON( data )
}
Now, even if the options argument is missing, the resulting URL would look like: /me/photos?access_token=....