How to set status code and headers in spray-routing based on a future result - spray

I'm using spray-routing with Akka to define a route like
def items = path("items") {
get {
complete {
actor.ask(GetItems)(requestTimeout).mapTo[Either[NoChange, Items]] map {
result => result match {
case Left(_) => StatusCodes.NotModified
case Right(items) =>
// here I want to set an HTTP Response header based on a
// field within items -- items.revision
items
}
}
}
}
}
The actor.ask returns a Future that gets mapped to a Future[Either[NoChange, Items]]. "complete" is happy to deal with the Future[StatusCodes...] or the Future[Items] but I'm not sure how to set an HTTP Response header within the Future.
If the header weren't being set within the Future then I could just wrap the complete in a directive but how do I set a header within the complete?
I'm using Spray 1.2.0.
Thanks for any pointers in the right direction!

If you are trying to do this inside of complete all branches of the expression inside must result in a type that can be marshalled by complete.
You could try a structure like this to make it work:
complete {
actor.ask(GetItems)(requestTimeout).mapTo[Either[NoChange, Items]] map {
result => result match {
case Left(_) => StatusCodes.NotModified: ToResponseMarshallable
case Right(items) =>
// here I want to set an HTTP Response header based on a
// field within items -- items.revision
val headers = // items...
HttpResponse(..., headers = headers): ToResponseMarshallable
}
}
}
This ensures that the type of the expression you pass to complete is Future[ToResponseMarshallable] which should always be marshallable.
A better way, though, is to use the onSuccess directive that lets you use other directives after a future was completed:
get {
def getResult() = actor.ask(GetItems)(requestTimeout).mapTo[Either[NoChange, Items]]
onSuccess(getResult()) {
case Left(_) => complete(StatusCodes.NotModified)
case Right(items) =>
// do whatever you want, e.g.
val extraHeaders = // items.revisions
respondWithHeaders(extraHeaders) {
complete(...)
}
}
}

Related

Issue with CRMContainer in Twilio Flex

I built a simple plugin that shows in the CRMContainer the url of my CRM given some attributes parameters (if they are passed by), during inbound tasks this works fine, but the problem is that during outbound calls the behaviour is not the one expected, this is the piece of code:
flex.CRMContainer.defaultProps.uriCallback = (task) => {
return task
? `https://mycrm.zzz/${task.attributes.clicar}/${task.attributes.contacth}/`
: 'https://mycrm.zzz/contacts/';
}
}
I would need an additional condition that tells the code, if this is an outbound voice call to always show a default url.
I tried adding an if/else that checks if task.attributes.direction is outbound, but Flex says this is undefined.
Any tip?
Thanks
Max
The problem is that you aren't checking for the existence of the task. Your original code had this:
flex.CRMContainer.defaultProps.uriCallback = (task) => {
return task
? `https://mycrm.zzz/${task.attributes.clicar}/${task.attributes.contacth}/`
: 'https://mycrm.zzz/contacts/';
}
}
Which returns the URL with the task attributes in it only if the task exists, because of the ternary conditional.
So, when you try to use the attributes you need to make sure the task exists. So taking your code from the last comment, it should look like this:
flex.CRMContainer.defaultProps.uriCallback = (task) => {
if (task) {
if (task.attributes.direction === 'outbound'){
return `https://mycrm.zzz/${task.attributes.clicar}/${task.attributes.contacth}/`;
} else {
return `https://mycrm.zzz/contacts/`
}
} else {
return 'https://mycrm.zzz/contacts/';
}
}

How to Jenkins Groovy scripting for live fetching of Docker image + authentication

I have a script groovy, this script for live fetching of docker image,
I want to add the authentication function with the private repository, but I am not familiar with groovy, who can help me, thanks
import groovy.json.JsonSlurper
// Set the URL we want to read from, it is MySQL from official Library for this example, limited to 20 results only.
docker_image_tags_url = "https://registry.adx.abc/v2/mysql/tags/list"
try {
// Set requirements for the HTTP GET request, you can add Content-Type headers and so on...
def http_client = new URL(docker_image_tags_url).openConnection() as HttpURLConnection
http_client.setRequestMethod('GET')
// Run the HTTP request
http_client.connect()
// Prepare a variable where we save parsed JSON as a HashMap, it's good for our use case, as we just need the 'name' of each tag.
def dockerhub_response = [:]
// Check if we got HTTP 200, otherwise exit
if (http_client.responseCode == 200) {
dockerhub_response = new JsonSlurper().parseText(http_client.inputStream.getText('UTF-8'))
} else {
println("HTTP response error")
System.exit(0)
}
// Prepare a List to collect the tag names into
def image_tag_list = []
// Iterate the HashMap of all Tags and grab only their "names" into our List
dockerhub_response.results.each { tag_metadata ->
image_tag_list.add(tag_metadata.name)
}
// The returned value MUST be a Groovy type of List or a related type (inherited from List)
// It is necessary for the Active Choice plugin to display results in a combo-box
return image_tag_list.sort()
} catch (Exception e) {
// handle exceptions like timeout, connection errors, etc.
println(e)
}
The problem has been resolved, thank you everyone for your help
// Import the JsonSlurper class to parse Dockerhub API response
import groovy.json.JsonSlurper
// Set the URL we want to read from, it is MySQL from official Library for this example, limited to 20 results only.
docker_image_tags_url = "https://registry.adx.vn/v2/form-be/tags/list"
try {
// Set requirements for the HTTP GET request, you can add Content-Type headers and so on...
def http_client = new URL(docker_image_tags_url).openConnection() as HttpURLConnection
http_client.setRequestMethod('GET')
String userCredentials = "your_user:your_passwd";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));
http_client.setRequestProperty ("Authorization", basicAuth);
// Run the HTTP request
http_client.connect()
// Prepare a variable where we save parsed JSON as a HashMap, it's good for our use case, as we just need the 'name' of each tag.
def dockerhub_response = [:]
// Check if we got HTTP 200, otherwise exit
if (http_client.responseCode == 200) {
dockerhub_response = new JsonSlurper().parseText(http_client.inputStream.getText('UTF-8'))
} else {
println("HTTP response error")
System.exit(0)
}
// Prepare a List to collect the tag names into
def image_tag_list = []
// Iterate the HashMap of all Tags and grab only their "names" into our List
dockerhub_response.tags.each { tag_metadata ->
image_tag_list.add(tag_metadata)
}
// The returned value MUST be a Groovy type of List or a related type (inherited from List)
// It is necessary for the Active Choice plugin to display results in a combo-box
return image_tag_list.sort()
} catch (Exception e) {
// handle exceptions like timeout, connection errors, etc.
println(e)
}
here is the result

cy.url() and/or cy.location('href') does not return a string

I have an editor page. When I add any content and click the "Save" button my URL will change, adding a random id in the URL. I want to check if my ID's are changing every time when I click the "Save button".
I save the URL result in variable and want to check it, I do it like this:
const currentURL = cy.url();
cy.get('.editor-toolbar-actions-save').click();
cy.url().should('not.eq', currentURL);
But my currentURL variable's type is not string:
expected http://localhost:8080/editor/37b44d4d-48b7-4d19-b3de-56b38fc9f951 to not equal { Object (chainerId, firstCall) }
How I can use my variable?
tl;dr
Cypress commands are asynchronous, you have to use then to work with their yields.
cy.url().then(url => {
cy.get('.editor-toolbar-actions-save').click();
cy.url().should('not.eq', url);
});
Explanation
A similar question was asked on GitHub, and the official document on aliases explains this phenomenon in great detail:
You cannot assign or work with the return values of any Cypress command. Commands are enqueued and run asynchronously.
The solution is shown too:
To access what each Cypress command yields you use .then().
cy.get('button').then(($btn) => {
// $btn is the object that the previous
// command yielded us
})
It is also a good idea to check out the core concepts docs's section on asynchronicity.
These commands return a chainable type, not primitive values like strings, so assigning them to variables will require further action to 'extract' the string.
In order to get the url string, you need to do
cy.url().then(urlString => //do whatever)
I have been having the same issue and so far most consistent method has been to save the URL to file and read it from file when you need to access it again:
//store the url into a file so that we can read it again elsewhere
cy.url().then(url => {
const saveLocation = `cypress/results/data/${Cypress.spec.name}.location.txt`
cy.writeFile(saveLocation, getUrl)
})
//elsewhere read the file and do thing with it
cy.readFile(`cypress/results/data/${Cypress.spec.name}.location.txt`).then((url) => {
cy.log(`returning back to editor ${url}`)
cy.visit(url)
})
Try this:
describe("Test Suite", () => {
let savedUrl;
beforeEach(() => {
cy.visit("https://duckduckgo.com/");
cy.url().then(($url) => {
savedUrl = $url;
});
});
it("Assert that theURL after the search doens't equal the URL before.", () => {
cy.get("#search_form_input_homepage").type("duck");
cy.get("#search_button_homepage").click();
// Check if this URL "https://duckduckgo.com/?q=duck&t=h_&ia=web"
// doesn't equal the saved URL "https://duckduckgo.com/"
cy.url().should("not.eq", savedUrl);
});
});
Refer below code snippet, Here you can get the current URL and store it in a variable, do print via cy.log()
context('Get Current URL', () => {
it('Get current url and print', () => {
cy.visit('https://docs.cypress.io/api/commands/url')
cy.url().then(url => {
const getUrl = url
cy.log('Current URL is : '+getUrl)
})
})
})
#Max thanks this helped to get some ideas on different versions.
The way I did it is:
Create a .json file in your fixtures folder (name it whatever you want).
On the new .json file, only add: { } brackets and leave the rest blank. The function will self populate that .json file.
Create a new function on the commands page to easily call it on your test.
It would probably be best to create two functions, 1 function to write url or the sliced piece of the url, and the another function to call it so you can use it.
A. Example of 1st method, this method cuts the id off of the URL and stores it on the .json file:
Cypress.Commands.add('writeToJSON', (nameOfJSONSlicedSection) =>
{
cy.url().then(urlID =>
{
let urlBit = urlID.slice(urlID.indexOf('s/') + 2, urlID.indexOf('/edit'))
cy.writeFile('cypress/fixtures/XYZ.json', {name: nameOfJSONSlicedSection, id: urlBit}) /*{ }<-- these will populate the json file with name: xxxxx and id:xxxxx, you can changes those to whatever meets your requirements. using .slice() to take a section of the url. I needed the id that is on the url, so I cut only that section out and put it on the json file.*/
})
})
B. 2nd example function of calling it to be used.
This function is to type in the id that is on the url into a search box, to find the item I require on a different it() block.
Cypress.Commands.add('readJSONFile', (storedJSONFile) =>
{
cy.readFile('cypress/fixtures/XYZ.json').its('id').then((urlSetter) => {
cy.log(storedJSONFile, 'returning ID: ' + urlSetter)
//Search for Story
cy.get('Search text box').should('be.visible').type(urlSetter, {delay: 75})
})
})
/*here I use a .then() and hold the "id" with "urlSetter", then I type it in the search box to find it by the id that is in the URL. Also note that using ".its()" you can call any part section you require, example: .its('name') or .its('id') */
I hope this helps!

unable to understand why validateOpt will return `None` instead of `JsError`

In the following code, I am unable to understand why validateOpt might return value JsSuccess(None) instead of JsError
def getQuestion = silhouette.UserAwareAction.async{
implicit request => {
val body: AnyContent = request.body
val jsonBodyOption: Option[JsValue] = body.asJson
jsonBodyOption.map((jsonBody:JsValue) => { //body is json
val personJsonJsResultOption = jsonBody.validateOpt[Person]//check that json structure is correct
personJsonJsResultOption match {
case personSuccessOption: JsSuccess[Option[Person]] => { //json is correct
val personOption = personSuccessOption.getOrElse(None) //why would getOrElse return None??
personOption match {
case Some(person) => {
... }
case None =>{ //I am not sure when this will be triggered.
...
}
}
}
}
case e: JsError => {
...
}
}
}
})
.getOrElse(//body is not json
...)
}
}
validateOpt by design considers success to be not only when body provides actual Person but also when Person is null or not provided. Note how documentation explains why JsSuccess(None) is returned:
/**
* If this result contains `JsNull` or is undefined, returns `JsSuccess(None)`.
* Otherwise returns the result of validating as an `A` and wrapping the result in a `Some`.
*/
def validateOpt[A](implicit rds: Reads[A]): JsResult[Option[A]]
Seems like your requirement is that Person must always be provided to be considered successful, so in this case validate should be used instead of validateOpt.

How to modify an URL in a view in CakePHP 2.x

It seems quite simple but there is something I am not able to figure out. I hope someone can help me fast.
I have an url, something like http://host/controller/action/argument/named:1/?query1=1. I want to add another query param to look it like http://host/controller/action/argument1/argument2/named:1/?query1=1&query2=2. I fact I want to add query2=2 to all URLs on a particular page, through some callback or something.
An URL may or may not have query params in the existing page URL.
How do I do it?
Example url : http://www.example.com/myController/myAction/param1:val1/param2:val2
You can use :
$this->redirect(array("controller" => "myController",
"action" => "myAction",
"param1" => "val1",
"param2" => "val2",
$data_can_be_passed_here),
$status,
$exit);
Hope it helps you.
May be I am thinking too much of it but here is how it came out. I put it in a UtilityHelper.
function urlmodify($params = array(), $baseurl = true) {
$top_level_1 = array('plugin', 'controller', 'action'); //top level vars
$top_level_2 = array('pass', 'named'); //top level vars
//for integrated use
$top_level = array_merge($top_level_1, $top_level_2);
$urlparams = array();
//get top level vars
foreach($top_level as $k) {
if(in_array($k, $top_level_1)) {
$urlparams[$k] = $this->request->params[$k];
}
if(in_array($k, $top_level_2)) {
$$k = $this->request->params[$k]; //create $pass & $named
}
}
//get query vars
if($this->request->query) {
$urlparams['?'] = $this->request->query;
}
//check for custom pass vars
if(isset($params['pass'])) {
$pass = array_merge($pass, $params['pass']);
}
//pass var has to be in numarical index
foreach($pass as $v) {
array_push($urlparams, $v);
}
//check for custom named vars
if(isset($params['named'])) {
$named = array_merge($named, $params['named']);
}
//pass var has to be in key=>value pair
foreach($named as $k=>$v) {
$urlparams[$k] = $v;
}
//check for custom query vars
if(isset($params['?'])) {
$urlparams['?'] = array_merge($urlparams['?'], $params['?']);
}
return Router::url($urlparams, $baseurl);
}
}
I have an URL: http://localhost/project/exlplugin/logs/manage_columns/1/a:1/n:1/?b=1. On some links I want to add some certain parameters. Here is the result when i call
echo $this->Utility->urlmodify(array('pass'=>array(2), 'named'=>array('m'=>2), '?'=>array('c'=>2)));*
It gives: http://localhost/thecontrolist/spreadsheet/logs/manage_columns/1/2/a:1/n:1/m:2?b=1&c=2
I just wanted to add just a query parameter to all my listing urls deleted=0 or deleted=1 for the SoftDelete thing :)
Thank you #u2460470 for the answer but it's just about modifying (not removing or creating anything but just adding some params to) current URL on a view page.

Resources