I'm working on a basic Twilio web application using Java and the Spark Java framework. I'm trying to have the user enter a number as input after the initial prompt through a Gather verb and then process that input. So far, I am able to call my Twilio number and it responds with the initial prompt, but after I enter a number it goes to /handle-number and crashes because the request did not contain any params and it can't find the "Digits" param (params is empty when I print it).
I have tried to mimic the API call via the Postman Chrome extension to debug it, but I get a 500 internal server error.
EDIT: Here is a screenshot of the postman request : Postman screenshot
I am new to Java web applications, HTTP requests, and Twilio, so I am unfamiliar with much of this. I have gone thought the twiml documentation and tutorials and tried to follow along but my I'm definitely missing something in my implementation.
How do I properly pass the phone input to the processNumber Route? Any help is appreciated!
App.java
import static spark.Spark.*;
public class App {
public static void main (String[] args){
post("/receive-call", ReceiveCall.call);
post("/handle-number", ReceiveCall.processNumber);
}
}
ReceiveCall.java
import com.twilio.twiml.voice.Gather;
import com.twilio.twiml.voice.Say;
import com.twilio.twiml.*;
import spark.Route;
public class ReceiveCall {
public static Route call = (request, response) -> {
Say sayMessage = new Say.Builder("Hello! Please enter a number as input. Enter # when finished.").build();
Gather input = new Gather.Builder().timeout(3).say(sayMessage).action("/handle-number").build();
VoiceResponse twiml = new VoiceResponse.Builder().gather(input).build();
System.out.println(response.body());
return twiml.toXml();
};
public static Route processNumber = ((request, response) -> {
String digit = request.params("Digits");
//CRASHES HERE BECAUSE digit IS NULL
int number = Integer.parseInt(digit);
Say message = process(number);
VoiceResponse twiml = new VoiceResponse.Builder().say(message).build();
return twiml.toXml();
});
The reason of "digit IS NULL" is: you are using request.params(...), which is for path parameter.
What is "path parameter"?
"path parameter" means passing parameter as part of URL path, especially in RESTful style request.
For example, if you want to send an HTTP GET request to retrieve a book by its ISBN, the request URL could be: /books/9787121022982 or /books/9787101054491, where the ISBN parameter is passed as part of URL path (9787121022982 and 9787101054491). In Spark framework, the corresponding Route code would be:
get("/books/:isbn", (request, response) -> {
return "Book ISBN is: " + request.params(":isbn");
});
What is "query parameter"?
"query parameter" means passing parameter as part of URL queries (entities after the ? character in URL).
Take the previous book ISBN case for example, if you want to pass ISBN as query parameter, the HTTP GET URL would be: /books?isbn=9787121022982, and the corresponding Spark Route code is:
get("/books", (request, response) -> {
return "Book ISBN is: " + request.queryParams("isbn");
});
What is the best practice to pass data in POST request?
In your case, the /handle-number route accept POST request. For HTTP POST request, it's not a good practice to pass data as parameter in URL. Instead, you need to pass data as request body, and get data from body in Spark code:
post("/handle-number", (request, response) -> {
String body = request.body();
// extract ISBN from request body string
});
Related
I am a .net developer and knows almost 0 to Cucumber or close to 0 about Java now (after 20 years not using it).
However, I was just given a Cucumber project used by other team (that team doesn't have java developer any more and no intention to hire any in future).
I can understand what Cucumber is doing, but there are some details I couldn't get.
For example, for this feature
#ChargesAPI
Scenario Outline: ChargesAPI project - Compare ChargesV2 VS ChargesV3 POST JSON Message
Given As a user i want to compare sheet ChargesAPI ChargesV2VsChargesV3 POST JSON output Message
When I POST given first <Iteration> URL DP:URI_1 and Json body DP:JSON_Message_1 content
And I POST given second <Iteration> URL DP:URI_2 and Json body DP:JSON_Message_2 content
Then I Compare both Output_Mess1 Output_Mess2 Output Message <Iteration>
Examples:
|Iteration|
|1|
|2|
|3|
|4|
|5|
|6|
|7|
|8|
|9|
|10|
|11|
|12|
|13|
|14|
|15|
looks like cucumber somehow will call our custom java code (maybe because it is defined in the cucumber.json file?)
public class POSTJSON_Steps {
private ActionContainer actcontainer;
public POSTJSON_Steps(ActionContainer actcontainer) {
this.actcontainer = actcontainer;
}
private String First_Mess;
private String Second_Mess;
#When("^I POST given first (.*) URL (.*) and Json body (.*) content")
public void I_POST_first_URL_and_JsonBody_content(int Itr,String strURI, String JSON) throws Exception {
First_Mess = actcontainer.postmethods.ThunderPostMethod(Itr,strURI,JSON);
}
#And("^I POST given second (.*) URL (.*) and Json body (.*) content")
public void I_POST_second_URL_and_JsonBody_content(int Itr,String strURI, String JSON) throws Exception {
Second_Mess = actcontainer.postmethods.ThunderPostMethod(Itr,strURI,JSON);
}
#Then("^I Compare both (.*) (.*) Output Message (.*)$")
public void I_Compare_QA_VS_Staging_Output_Message(String strFstJSON, String strSndJSON,int Itr) throws Exception {
actcontainer.storedata.StoreJSONMessAsJson(Itr,strFstJSON,strSndJSON, First_Mess,Second_Mess);
actcontainer.comparedata.CompareJSONOutput(Itr,First_Mess, Second_Mess);
}
}
I wanted to print out parameter detail in out PostMethods.java (basically try to print some debugging info)
public class POSTMethods {
public String ThunderPostMethod(int itr,String strURL, String JSONBody) throws Exception {
String strContent = null;
strContent = RESTClient.POSTREQUEST(itr, strURL, JSONBody, "Authorization/Bearer "+TokenGenerate.AuthToken());
System.out.println("strContent:"+strContent);
System.out.println("strURL:"+strURL);
System.out.println("JSONBody:"+JSONBody);
strContent = PostJSONSorting.POST_JSONValue(strContent,itr,strURL, JSONBody);
return strContent;
}
}
However, the print always return this:
strURL:DP:URI_1 JSONBody:DP:JSON_Message_1
So looks like cucumber has some way to replace DP:URI_1 and DP:JSON_Message_1 to the real url and message?
I just want to find a way to print out the url and message this code is sending, is there a way?
I am trying to read data from reddit using java. I am using JRAW.
Here is my code:
public class Main {
public static void main(String args[]) {
System.out.println('a');
String username = "dummyName";
UserAgent userAgent = new UserAgent("crawl", "com.example.crawl", "v0.1", username);
Credentials credentials = Credentials.script(username, <password>,<clientID>, <client-secret>);
NetworkAdapter adapter = new OkHttpNetworkAdapter(userAgent);
RedditClient reddit = OAuthHelper.automatic(adapter, credentials);
Account me = reddit.me().about();
System.out.println(me.getName());
SubmissionReference submission = reddit.submission("https://www.reddit.com/r/diabetes/comments/9rlkdm/shady_insurance_work_around_to_pay_for_my_dexcom/");
RootCommentNode rcn = submission.comments();
System.out.println(rcn.getDepth());
System.out.println();
// Submission submission1 = submission.inspect();
// System.out.println(submission1.getSelfText());
// System.out.println(submission1.getUrl());
// System.out.println(submission1.getTitle());
// System.out.println(submission1.getAuthor());
// System.out.println(submission1.getCreated());
System.out.println("-----------------------------------------------------------------");
}
}
I am making two requests as of now, first one is reddit.me().about(); and the second is reddit.submission("https://www.reddit.com/r/diabetes/comments/9rlkdm/ shady_insurance_work_around_to_pay_for_my_dexcom/");
The output is:
a
[1 ->] GET https://oauth.reddit.com/api/v1/me?raw_json=1
[<- 1] 200 application/json: '{"is_employee": false, "seen_layout_switch": true, "has_visited_new_profile": false, "pref_no_profanity": true, "has_external_account": false, "pref_geopopular": "GL(...)
dummyName
[2 ->] GET https://oauth.reddit.com/comments/https%3A%2F%2Fwww.reddit.com%2Fr%2Fdiabetes%2Fcomments%2F9rlkdm%2Fshady_insurance_work_around_to_pay_for_my_dexcom%2F?sort=confidence&sr_detail=false&(...)
[<- 2] 400 application/json: '{"message": "Bad Request", "error": 400}'
Exception in thread "main" net.dean.jraw.ApiException: API returned error: 400 (Bad Request), relevant parameters: []
at net.dean.jraw.models.internal.ObjectBasedApiExceptionStub.create(ObjectBasedApiExceptionStub.java:57)
at net.dean.jraw.models.internal.ObjectBasedApiExceptionStub.create(ObjectBasedApiExceptionStub.java:33)
at net.dean.jraw.RedditClient.request(RedditClient.kt:186)
at net.dean.jraw.RedditClient.request(RedditClient.kt:219)
at net.dean.jraw.RedditClient.request(RedditClient.kt:255)
at net.dean.jraw.references.SubmissionReference.comments(SubmissionReference.kt:50)
at net.dean.jraw.references.SubmissionReference.comments(SubmissionReference.kt:28)
at Main.main(Main.java:36)
Caused by: net.dean.jraw.http.NetworkException: HTTP request created unsuccessful response: GET https://oauth.reddit.com/comments/https%3A%2F%2Fwww.reddit.com%2Fr%2Fdiabetes%2Fcomments%2F9rlkdm%2Fshady_insurance_work_around_to_pay_for_my_dexcom%2F?sort=confidence&sr_detail=false&raw_json=1 -> 400
... 6 more
As it can been that my first request gives me a response of my username but in the second response i am getting a bad request 400 error.
To check whether my client ID and client secret were working correctly I did the same request using python PRAW library.
import praw
from praw.models import MoreComments
reddit = praw.Reddit(client_id=<same-as-in-java>, client_secret=<same-as-in-java>,
password=<same-as-in-java>, user_agent='crawl',
username="dummyName")
submission = reddit.submission(
url='https://www.reddit.com/r/redditdev/comments/1x70wl/how_to_get_all_replies_to_a_comment/')
print(submission.selftext)
print(submission.url)
print(submission.title)
print(submission.author)
print(submission.created_utc)
print('-----------------------------------------------------------------')
This gives the desired result without any errors so the client secret details must be working.
The only doubt I have is in the user agent creation in java UserAgent userAgent = new UserAgent("crawl", "com.example.crawl", "v0.1", username);.
I followed the following link.
What exactly does the target platform, the unique ID or the version mean. I tried to keep the same format as in the link. Also using the same username as in other places. On the other hand the user_agent in python was a string crawl.
Please tell me if I am missing anything and what could be the issue.
Thank you
P.S. I want to do this in java. not python.
Since your first query is working the credentials are correct. In JRAW don't give the whole URL but only the id in the submission function.
Change this
SubmissionReference submission = reddit.submission("https://www.reddit.com/r/diabetes/comments/9rlkdm/shady_insurance_work_around_to_pay_for_my_dexcom/");
to this
SubmissionReference submission = reddit.submission("9rlkdm");
where the id is the random string after /comment/ in the URL.
Hope this helps.
I'm working on Lagom POC on sending POST request to Non lagom service with custom Header. In my case I'm trying to hit postman-echo to test the custom header.
However, it looks the headers are not set though I made code changes accordingly:
public CompletionStage<DsapAuthorizationResponse> hitAPI(AuthorizationRequest request) {
DsapWSRequest dsapWSRequest = new DsapWSRequest();
dsapWSRequest.username = request.username;
dsapWSRequest.password = request.password;
CompletionStage<DsapAuthorizationResponse> dsapresponse = dsapExternalService
.authenticate()
.handleRequestHeader(requestHeader -> {
requestHeader.withHeader("Authorization","Basic mncndsjna");
System.out.println("My Headers>>>>>>>> " + requestHeader);
return requestHeader;
})
.handleResponseHeader((responseHeader,b) -> {
System.out.println("RESPonse Header >>>>>>> : "+responseHeader);
return b;
})
.invoke(dsapWSRequest);
return dsapresponse;
}
In the above code header authorization is not set in the request. I am not getting this header in the echo which is mapped correctly in my POJO.
here is the complete code from my GitHub
https://github.com/sourabhsar/Lagom-Unmanaged-Service-Demo/tree/poc/lagom-request-response
I followed the steps mentioned here:
https://groups.google.com/forum/#!topic/lagom-framework/yvKmqvtZWFs
and also followed few other blogs/articles.
However so far I haven't found any blog which they are sending request to unmanaged external service with custom header. I'm not sure whats wrong in my code.
requestHeader.withHeader returns a new object with the added header, but the code you have written returns the original requestHeader object. In general, many Lagom APIs follow a principle of using immutable objects, with methods that return a new, modified instance, rather than changing the instance the method is called on.
Try this:
.handleRequestHeader(requestHeader -> {
RequestHeader modifiedRequestHeader =
requestHeader.withHeader("Authorization","Basic mncndsjna");
System.out.println("My Headers>>>>>>>> " + modifiedRequestHeader);
return modifiedRequestHeader;
})
I tried using
String userAgent=req.getHeader("user-agent");
and also the following
#GET
#Path("/get")
public Response addUser(#HeaderParam("user-agent") String userAgent) {
return Response.status(200)
.entity("addUser is called, userAgent : " + userAgent)
.build();
}
But I need only, browser name as chrome,firefox,IE.Please help,if anyone know.
UPDATE : Got answer
public String browser(#HeaderParam("user-agent") String userAgent){
UserAgent browserName = UserAgent.parseUserAgentString(userAgent);
String browser=browserName.toString();
System.out.println(browser)
}
Getting information out of user agent strings is somewhat of a black art. Easiest is probably to use a library to parse the user agent string and extract the needed information.
I've used UADetector in the past with good results, but there are undoubtedly other libraries out there.
The following sample is from the UADetector documentation:
UserAgentStringParser parser = UADetectorServiceFactory.getResourceModuleParser();
ReadableUserAgent agent = parser.parse(request.getHeader("User-Agent"));
out.append("You're a <em>");
out.append(agent.getName());
out.append("</em> on <em>");
out.append(agent.getOperatingSystem().getName());
out.append("</em>!");
I am making the following AJAX request:
$.post('/route', {
arg1 : 'foo',
arg2 : 'bar'
});
Through the route:
POST /route controllers.Test.readPost()
How do I access these POST variables in the method of my controller?
public static Result readPost() {
return TODO; // read post variables
}
I cannot find a simple way of doing this in the documentation. It only states how to get values from JSON requests.
Use DynamicForm
public static Result getValues(){
DynamicForm requestData = form().bindFromRequest();
String name = requestData.get("name");
String desg = requestData.get("desg");
// etc
return ok("You sent: " + name + ", " + desg);
}
There is also other possibility to construct AJAX query and pass arguments via javascriptRoutes: https://stackoverflow.com/a/11133586/1066240
Of course it will pass the params via URL so it's not suitable for every value, but in many places it will be goot enough for sending POST requests with AJAX. Of course javascriptRoutes create the request with type set in routes file.
BTW: it was better if you wrote which version you are using.
you can use GET with an ajaxRequest. more information can be found here http://www.javascriptkit.com/dhtmltutors/ajaxgetpost.shtml
var mygetrequest=new ajaxRequest()
mygetrequest.onreadystatechange=function(){
if (mygetrequest.readyState==4){
if (mygetrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("result").innerHTML=mygetrequest.responseText
}
else{
alert("An error has occured making the request")
}
}
}
var namevalue=encodeURIComponent(document.getElementById("name").value)
var agevalue=encodeURIComponent(document.getElementById("age").value)
mygetrequest.open("GET", "basicform.php?name="+namevalue+"&age="+agevalue, true)
mygetrequest.send(null)