Currently, I'm testing out features of Twilio. I simply wanted to get two numbers from the user representing a username and password. What happens is because I don’t know what address to put in action, it defaults to the same time and loops the first gather over and over again. Currently, I’m using Spark and ngrok to test my code.
package com.example;
import com.twilio.twiml.VoiceResponse;
import com.twilio.twiml.voice.Gather;
import com.twilio.twiml.voice.Say;
import static spark.Spark.*;
public class Example {
public static void main(String[] args) {
post("/", (request, response) -> {
Say say = new Say.Builder(
"Enter UserID.")
.build();
Gather gather = new Gather.Builder().action("/").say(say).build();
Say say2 = new Say.Builder(
"Enter Password.")
.build();
Gather gather2 = new Gather.Builder().action("/").say(say2).build();
VoiceResponse voiceResponse = new VoiceResponse.Builder()
.gather(gather)
.gather(gather2)
.build();
return voiceResponse.toXml();
});
}
}
I tried changing the action attribute to a random address like /test, I changed the method to POST or GET, but neither seemed to have any effect except in the ngrok dashboard. The problem I'm currently having is I have no clue how to use Spark and the Gather verb together.
It repeats the actions over and over again because of the properties of the gather TwiMl element.
First, you should point to a different endpoint of your application and handle the response at this endpoint. Once you parse the user input at this endpoint, you can return another TwiML response that asks for the second input, which you then need to process at a third endpoint.
With this in mind, I see a second problem with the code above. You ask for both inputs sequentially, meaning you only ask for the second input if the caller ignores the first prompt and remains quiet. Look at "Scenario 1-3" of this page for more details.
I understand that implementing so many endpoints for a simple IVR might be confusing at first. The good news is that this can be much simpler by using Studio.
Related
I have set up this simple http request, which simply returns a "hello world" response to my IDE terminal. I have been looking into testing and I am not quite sure how i would test what this method is returning.
Currently i have done my own research into JUnit, but again i am not even sure if this would be the correct tool to use for this problem. I only researched this as it is a Java tool.
public static void newRequest() throws IOException {
URL helloServer = new URL("http://localhost:5050/");
HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(helloServer));
HttpResponse rawResponse = request.execute();
String responseString = rawResponse.parseAsString();
logger.debug(responseString);
}
Any guidance on this would be greatly appreciated.
Does the function even need to be tested?
Does the function even need to be tested? Well, that is entirely up to you. Does this function contain code that is critical to your application? If so then yes. If the impact of a bug in this function is minimal then probably not.
Assuming that you want to test this, then:
The method in question is not returning anything void before the function name says this. You will need to look at testing the logic of the function. In this case you need to check that the correct response is received. There are two ways that I can think of to do this:
Modify the code to return the response.
You could change the function to return a String and then return rawResponse.parseAsString(); (which is the same thing you are logging.
Then you can call the function from the test and check the String that is returned.
Get the log message from your logger.
Depending on the logging that you are using, you could get the log message that was written by the function. Assuming log4j then there are some posts on how to do this:
log4j: how to get the last inserted log message?
Personally, I prefer the first option as it is less effort. I would also consider returning the body of the response rather than the raw response.
Consider I have below feature files:
Login.feature
Feature: Login on website
Scenario: Login verification on site
Given Navigate to site login page
When User enters username 'admin1'
And User enters password 'admin1'
And User clicks on login button
Then User should not be able to log in successfully
Home.feature
Feature: Welcome Page Verification
Scenario: Verify the page that comes after login
Given Login is successfully done
When The page after login successfully appears
Then The test is done
In Home.feature file, I need to execute Login.feature first and then call home.feature. So when i execute home from my runner test it will in turn execute login and then home.
RunnerTest.java
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(strict = false, features = {
"src/test/resources/Features/Home.feature",
}, glue = { "tests" }, plugin = "html:target/cucumber-reports", format = { "pretty",
"json:target/cucumber.json" }, tags = { "~#ignore" })
public class RunnerTest {}
You don't need to call the first feature from the second feature. What you need to do is have a step in the second feature that can log you in. It can do this by calling code you've created when implementing your first feature.
The first feature is something you might write when you are implementing login for the first time. In doing this you will steps and code that these steps call to log you in.
The sort of code you should be creating is (sorry all examples are ruby i don't do java)
A test user entity that knows its name, email and password
A method that can user the test user to login
Then you can write a helper method e.g.
def login_as(user)
visit login_path
fill_in :email, with: user.email
fill_in :password, with: user.password
submit_form
end
and now in your second feature you can have something like
Given I am an admin
When I login
and implement these steps as
Given 'I am an admin' do
# note create_user is a method you would have created when doing user
# registration/creation
#i = create_user(type: admin)
end
When "I login" do
login_as #i
end
and somewhere you will have some helper methods
module StepHelperMethods
def create_user
...
return user
end
def login_as(user)
...
end
end
World StepHelperMethods
Your code reuse always happens at a much lower level. Ideally you should be re-using helper methods that you have created previously to make other scenarios work. You can also call steps directly (nested steps) but this is a very bad thing to do.
Try this:
Create a RunnerLogin class to call the Login.feature.
In your steps class, in the method that implements the
Given Login is successfully done, do something like:
#Given("^Login is successfully done$")
public void login_is_successfully_done() {
Thread T1 = new Thread(new Thread(() -> {
JUnitCore jExecFeature = new JUnitCore();
Result result = jExecFeature.run(RunnerLogin.class);
}));
T1.start();
T1.join();
}
Behind every feature there is a method implemented in your step definitions, so you will not need to write your features in that manner, you will just need to call the method that you have already implemented.
The best solution for frequently used functionalities of your application like Login for e.g is to have Helper methods.
You can implement these methods as global and use them in your every step definition file.
public void LoginUserGlobal(String user, String pass) throws Throwable {
LoginPageObjects LP = new LoginPageObjects(driver);
LP.user().sendKeys(user);
LP.pass().sendKeys(pass);
LP.loginButton().click();
}
And if you need to use it in any of your features you will code it like:
#When("^User logs in with \"([^\"]*)\" and \"([^\"]*)\"$")
public void user_logs_in_with_something_and_something(String user, String pass) throws Throwable {
GlobalClassWhereIsYourLoginMethod Lin = new GlobalClassWhereIsYourLoginMethod (driver)
LoginUserGlobal(user,pass);
}
or if it is not so used part of app, you will call it from a step definition method where is already implemented.
I want to learn how to:
Step1: open URL – for example Gmail
Step 2: insert user and password and press sign-in.
How can I inset user and password and press the sign-in button?
Do I need/must use selenium?
This code is only for open the browser(step 1)
import java.io.IOException;
public class Website
{
public void openWebsite() //throws IOException
{
try
{
#SuppressWarnings("unused")
Process p = Runtime.getRuntime().exec("cmd /c start http://accounts.google.com/ServiceLogin ");
}
catch (IOException e1)
{
System.out.println(e1);
}
}
}
First you need to open the URL. Right now you are actually not opening the URL. You are asking the Windows operating system "What would you do with http://accounts.google.com/ServiceLogin?"
Because it is windows, it will make a guess, which sort of follows this line of logic:
it sort of looks like a URL, so I'll fire up explorer and
ask explorer to do something with it.
Which means that your code is now a few programs away from being able to get the data, and none of the intermediate programs will (because they're not built to do so), transmit the need for input into your program.
What you need to do is to avoid asking other programs to open the URL, it's just too problematic. First, they might get it wrong, second they'll never know how to ask you the input. To open a URL directly:
import java.net.URL;
... somewhere in the code ...
URL url = new URL("http://accounts.google.com/ServiceLogin");
InputStream in = url.openStream();
do some googling on various java.net.URL tutorials, and you will soon find the right combination of techniques needed to handle your particular credential challenge. Here's one resource, but it seems you need to do a bit of homework before what they say will make sense to you. If you stumble, at least you'll have a better, more specific question to ask the next time around (and don't forget to post your source code).
I'm trying to download www.pandora.com/profile/stations/olin_d_kirkland HTML with Java to match what I get when I select 'view page source' from the context menu of the webpage in Chrome.
Now, I know how to download webpage HTML source code with Java. I have done it with downloads.nl and tested it on other sites. However, Pandora is being a mystery. My ultimate goal is to parse the 'Stations' from a Pandora account.
Specifically, I would like to grab the Station names from a site such as www.pandora.com/profile/stations/olin_d_kirkland
I have attempted using the selenium library and the built in URL getter in Java, but I only get ~4700 lines of code when I should be getting 5300. Not to mention that there is no personalized data in the code, which is what I'm looking for.
I figured it was that I wasn't grabbing the JavaScript or letting the JavaScript execute first, but even though I waited for it to load in my code, I would only always get the same result.
If at all possible, I should have a method called 'grabPageSource()' that returns a String. It should return the source code when called upon.
public class PandoraStationFinder {
public static void main(String[] args) throws IOException, InterruptedException {
String s = grabPageSource();
String[] lines = s.split("\n\r");
String t;
ArrayList stations = new ArrayList();
for (int i = 0; i < lines.length; i++) {
t = lines[i].trim();
Pattern p = Pattern.compile("[\\w\\s]+");
Matcher m = p.matcher(t);
if (m.matches() ? true : false) {
Station someStation = new Station(t);
stations.add(someStation);
// System.out.println("I found a match on line " + i + ".");
// System.out.println(t);
}
}
}
public static String grabPageSource() throws IOException {
String fullTxt = "";
// Get HTML from www.pandora.com/profile/stations/olin_d_kirkland
return fullTxt;
}
}
It is irrelevant how it's done, but I'd like, in the final product, to grab a comprehensive list of ALL songs that have been liked by a user on Pandora.
The Pandora pages are heavily constructed using ajax, so many scrapers struggle. In the case you've shown above, looking at the list of stations, the page actually puts through a secondary request to:
http://www.pandora.com/content/stations?startIndex=0&webname=olin_d_kirkland
If you run your request, but point it to that URL rather than the main site, I think you will have a lot more luck with your scraping.
Similarly, to access the "likes", you want this URL:
http://www.pandora.com/content/tracklikes?likeStartIndex=0&thumbStartIndex=0&webname=olin_d_kirkland
This will pull back the liked tracks in groups of 5, but you can page through the results by increasing the 'thumbStartIndex' parameter.
Not an answer exactly, but hopefully this will get you moving in the correct direction:
Whenever I get into this sort of thing, I always fall back on an HTTP monitoring tool. I use firefox, and I really like the Live HTTP Headers extension. Check out what the headers are that are going back and forth, then tailor your http requests accordingly. As an absolute lowest level test, grab the header from a successful request, then send it to port 80 using telnet and see what comes back.
Can somebody give a simple example for java code of a native app passing a string to a website?
For example: when a string has the value Hello everybody, the text Hello everybody should get pasted into the Google search field.
For the most simple use, you can try:
public static void browseURL(Activity activity, String url)
{
try
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
activity.startActivity(intent);
}
catch (Exception e)
{
message(activity, "Sorry, failed to view the desired page.");
}
}
and then call:
browseURL("http://www.google.com/search?q=Hello+World")
Do you want to fill the fields and submit them? If so, just do the request with the request parameters filled, and parse the response given by the server. Look into Apache HttpClient.
You don't actually have to add text to the Google search field explicitly. You can send a URL with a query string.
Depending on the website the query string will always be different. For Google it is http://www.google.ca/search?q=something . Anything after a ? is considered a query string which any good web developer will include in a webpage. That query string takes custom commands in the form of ?command=query for command&command2=query for command 2.
Since this is tagged blackberry, I assume you want to implement a blackberry app, and you don't explicitly explain what you want to do, so you have two options,
Invoke the browser
On that page it describes how to open a browser session. So within the
browserSession.displayPage("http://http://www.google.ca/search?q=searching%20for%20something");
If you need a class for URL encoding, let me know and I'll send one your way.
Http Request to pull the html of the webpage into the code. To do that, you'll have to look at my blog this week as I'll be posting a full in code network class either tomorrow or tuesday, which I'll edit this post to contain a link to.
OR you can send me a message if you need it NOW and I can email the non-cleaned up code to you.