routing help in Txroutes library - url

I need to route the following to a function :
http://www.example.com/docs/?key1=value1&key2=value2
And the route code for it is
dispatcher.connect(name='xyz', route='/docs/{item}', controller=c, action='docs')
so, can you help me with the “route” part as in what should come there so for an incoming request the action gets called.
As in how to relate route='/docs/{item}' and /docs/?key1=value1&key2=value2

HTTP GET request (/docs/) followed by a query string (?key1=value1&key2=value2). You'd use Twisted's normal facilities for accessing the query string.
def docs(self, request):
return '<html><body>Got %s args</body></html>' % request.args
to retrieve from the array use request.args['key1'][0] to get 'value1'.

Related

Replacing slack app mentions with usernames in the slack message log in Dataweave

I'm parsing the slack message log from conversations.history and any app mentions come in as <#XX12345>. I'm trying to parse the XX12345 part in a conversation and replace it with username and get rid of the < and >. For eg:
Hello <#UA12345> how are you?
I'm good <#UA67890>. How about you?
should become
Hello #lookup(UA12345) how are you?
I'm good #lookup(UA67890). How about you?
How do I achieve this using replace and regex in DataWeave? The lookup function is used to get the user name from Slack API. This function also needs to be triggered inside Dataweave (not sure if this is even possible). End result would be something like this:
Hello #Adam how are you?
I'm good #David. How about you?
Assuming the username in <#UA67890> is alphanumeric, you can use the following expression to get the required result
yourText replace /\<\#([a-zA-Z0-9]*)\>/ with "#$(getUsername($[1]))"
This matches the regex \<\#([a-zA-Z0-9]*)\> which captures alphanumeric value in between a <# and > in a group and then replace it with #$(getUsername($[1])), i.e. #getUsername(everything that was captured as in the above group)
You can create the function getUsername to actually call the lookup function and call the required flow. So your DataWeave will look something like this.
%dw 2.0
output text/plain
fun getUsername(userid) = lookup('get-user-name-flowname', userid) // Any other transformation that you may need for passing the required payload before calling loopup
var conversation =
"Hello <#UA12345> how are you?
I'm good <#UA67890>. How about you?"
---
conversation replace /\<\#([a-zA-Z0-9]*)\>/ with "#$(getUsername($[1]))"
Update: As mentioned in comment, you also need a flow get-user-name-flowname that will either use slack's REST API or <slack:get-usersprofileget> which will accept this ID and will return the username of the user

Accessing Twitter with Akka Camel to return JSON

I was using an HTTP POST method using the URL
"https://stream.twitter.com/1.1/statuses/filter.json" and in the body I was posting the key/value I wanted to get tweets from - for example "track=london". This was working fine.
Now I am trying to switch to AKKA-CAMEL and I am using their twitter consumer. I am using an endpoint URL of:
def endpointUri: String = s"twitter:////search?type=direct&keywords=${Settings.queryList()}&consumerKey=${tweeterCredentials.consumerKey}&consumerSecret=${tweeterCredentials.consumerSecret}&accessToken=${tweeterCredentials.accessToken}&accessTokenSecret=${tweeterCredentials.accessTokenSecret}"
I get a response from twitter but it is not in JSON and it is not the same information about the tweet as before. It just return the tweet text but before I was getting the whole metadata which I need to analyze.
Does somebody knows how to configure Camel URI to return JSON and the whole metadata as before?
Thanks
I got this to work by using the following syntax:
def endpointUri: String = s"twitter://streaming/filter?type=event&keywords=${Settings.queryList()}&consumerKey=${tweeterCredentials.consumerKey}&consumerSecret=${tweeterCredentials.consumerSecret}&accessToken=${tweeterCredentials.accessToken}&accessTokenSecret=${tweeterCredentials.accessTokenSecret}"
Where: Settings.queryList return a comma separated list of keyworkds. The object tweeterCredentials holds the keys from Tweeter to access the site.
Also it is necessary to set autoAck like this in Camel:
override def autoAck = true
This prevents a timeout exception.

HTTPClient GetAsync post object

We currently have a generic MVC method that GET's data from ASP.NET Web API
public static T Get<T>(string apiURI, object p)
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(Config.API_BaseSite);
HttpResponseMessage response = client.GetAsync(apiURI).Result;
// Check that response was successful or throw exception
if (response.IsSuccessStatusCode == false)
{
string responseBody = response.Content.ReadAsStringAsync().Result;
throw new HttpException((int)response.StatusCode, responseBody);
}
T res = response.Content.ReadAsAsync<T>().Result;
return (T)res;
}
}
Our question is:- obviously, we can not send 'p' as you would with a post,
client.PostAsync(apiURI, new StringContent(p.ToString(), Encoding.UTF8, "application/json")
but how we go about sending this object / JSON with a get.
We have seen sending it as part of the URL, however, is there an alternative?
GET sends the values with the query string (end of url), in regards to "but how we go about sending this object / JSON with a get. We have seen sending it as part of the URL, however, is there an alternative?".
The alternative is POST or PUT.
PUT is best used when the user creates the key/url. You can look at examples such as cnn.com - where the URL's are just short versions of the article title. You want to PUT a page at that URL.
Example:
http://newday.blogs.cnn.com/2014/03/19/five-things-to-know-for-your-new-day-wednesday-march-19-2014/?hpt=hp_t2
has the url of "five-things-to-know-for-your-new-day-wednesday-march-19-2014", which was generated from the article title of "Five Things to Know for Your New Day – Wednesday, March 19, 2014"
In general, you should follow these guidelines:
Use GET when you want to fetch data from the server. Think of search engines. You can see your search query in the query string. You can also book mark it. It doesn't change anything on the server at all.
Use POST when you want to create a resource.
Use PUT when you want to create resources, but it also overwrites them. If you PUT an object twice, the servers state is only changed once. The opposite is true for POST
Use DELETE when you want to delete stuff
Neither POST nor PUT use the query string. GET does

Jersey POST operation with PathParam and JSON Object

By design, GET operation should be used only for read Only operation. Howeevre,i am looking for a plausible way of implementaion of following.Implement a POST operation that can be called as it is mentioned below
POST /my-store/order/D : where D is the day the customer place an order
Request: POST /my-store/order/14
{
"customer" : "XYZ",
"order" : {
"item1" : 2
}
}
I tried implementing using below function
#Path("/D")
#POST
#Consumes({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON })
#Produces({ MediaType.APPLICATION_JSON })
public Response submitOrder(#PathParam("D") int elapsedDays, #Context UriInfo uriInfo, Order orderInfo){
..........
}
But the above implementation does not seem to working. When I try to test the implementation using MyEclipse REST explorer ,it does not offer option to pass in Order object but allow 'D' parameter only. However, if #PathParam and #Path is removed then it works perfectly fine i.e. allows to consume JSON Order object.
But,the requirement is to pass the days as Path parameter and Order object as JSON input in POST request.
Looking for suggestion on implementation approach and design approach.
Thanks in advance
For one thing, your path should be configured like this:
#Path("/{D}")
I assume your extended ellipses means you have some method parameter that represents the deserialization of your order.

How to get the request URI in Grails?

I've got a simple Grails app with the following RESTful uri...
http://localhost:8080/kennis-api/funds/test/700
The mapping in my URIMappings is
"/funds/test/$fcode" (controller: "fundCache"){
action = [GET: "show"]
}
In my controller, I need to extract the request URI, in this case "/funds/test/700", but invoking request.uri or request.getRequestUri does not work. I tried using request.requestURL, but that gives me
http://localhost:8080/kennis-api/grails/fundCache/show.dispatch
Is there a special member or function from which to get the request uri?
Its Simple, You need the Original address, that is same as the one where your response will be forwarded, its simply stored in the Request, and can be retrieved by:
.
String originalURI = request.forwardURI
//Do this where request is available, ex: Controllers :)
// Everywhere else you can use RequestContextHolder
.
.
Hope that helps
Regards
Kushal

Resources