NullPointerException in Gdx.net.sendHttpRequest - java

I have tried to write a little code using libGDX to work with network. Here's a code:
public class Test {
public static void main(String[] args) {
String accessToken = "********"; //a set of symbols, not important because it is specific of request target
String userID = "*********"; //also not important
String message = "Hello World";
String uri = "method/wall.post?owner_id=" + userID + "&message=" + message + "&access_token=" + accessToken;
HttpRequestBuilder requestBuilder = new HttpRequestBuilder();
HttpRequest httpRequest = requestBuilder.newRequest().method(HttpMethods.GET).url("https://api.vk.com/").content(uri).build();
Gdx.net.sendHttpRequest(httpRequest, //Here Eclipse shows NullPointerException
null); //But not here
}
If I write this URL in browser, it works right. It means, that the problem on my side. How to fix it?
Summary of values of the object which causes NullPointerException:

You are writing this code in the static main entry point of your program. Your Gdx is not yet loaded,so Gdx is still null at this point.
Create a none static class and put your code in it's constructor and initialize that class within this static entry point.
public class WebTest()
{
public WebTest()
{
String accessToken = "********"; //a set of symbols, not important because it is specific of request target
String userID = "*********"; //also not important
String message = "Hello World";
String uri = "method/wall.post?owner_id=" + userID + "&message=" + message + "&access_token=" + accessToken;
HttpRequestBuilder requestBuilder = new HttpRequestBuilder();
HttpRequest httpRequest = requestBuilder.newRequest().method(HttpMethods.GET).url("https://api.vk.com/").content(uri).build();
Gdx.net.sendHttpRequest(httpRequest, //Here Eclipse shows NullPointerException
null); //But not here
}
}
public class Test {
public static void main(String[] args) {
new WebTest();
}
}

Related

Controlling events of a Twilio call

In the next sample code, Twilio puts in conversation OPERATOR_PHONE_NUMBER to CLIENT_PHONE_NUMBER, and records the call.
But I don't know what should be the code to control some things, one or both of the phones...:
does not exist.
exists but communicates.
exists, does not communicate but does not pick up.
exists, does not communicate, picks up and the conversation takes place.
import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Call;
import com.twilio.rest.api.v2010.account.CallCreator;
import com.twilio.type.PhoneNumber;
import com.twilio.type.Twiml;
public class SimpleCallWithRecording2 {
private static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
private static final String AUTH_TOKEN = "9ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ";
private static final String ASSIGNED_PHONE_NUMBER = "+15999999999999";
//Must be verified numbers in trial account
private static final String OPERATOR_PHONE_NUMBER = "+34888888888";
private static final String CLIENT_PHONE_NUMBER = "+34777777777";
public static void main(String[] args) throws Exception {
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
PhoneNumber to = new PhoneNumber(OPERATOR_PHONE_NUMBER);
PhoneNumber from = new PhoneNumber(ASSIGNED_PHONE_NUMBER);
Twiml twiml = new Twiml(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?> " +
"<Response> " +
" <Say voice=\"woman\">This is said by a robotic woman</Say> " +
" <Dial> " +
" <Number> " + CLIENT_PHONE_NUMBER + "</Number> " +
" </Dial> " +
"</Response> " );
CallCreator callCreator = Call.creator(to, from, twiml);
callCreator.setRecord(true);
Call call = callCreator.create();
System.out.println(call);
}
}
In the doc I see something could be done with callCreator.setStatusCallback(URI.create("https://www.myapp.com/events")), and some clasification of events: "initiated", "ringing", "answered", "completed". BUT I havent find the code "on the other side", I mean in https://www.myapp.com/events extreme ¿?
You need to setup a that rest endpoint and set it as status callback url.
The url will recieve events from twilio.
Refer this
edit: if you also need events from the nested verb, define attribute 'action' to it.
ie
<Dial action="//callbackURL">
<Number> CLIENT_PHONE_NUMBER </Number>
</Dial>
that way you'll know your cases 1 ,2 ,3 ,4.
and to "control" the call, you just respond with the desired TwiML to the callback request. Hope this clarifies.
edit2: You need to do something like:
//handles callback url
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
{ //...
TwiMLResponse twiml = new TwiMLResponse();
String callSid = request.getParameter("CallSid");
//handle call specific data
switch(request.getParameter("CallStatus")){
case "no-answer": //construct twiML
case "ringing" ://...
}
//...
response.setContentType("application/xml");
response.getWriter().print(twiml.toXML());
}
See: IVR - Example

Inheriting a remote webdriver syntax

I want to inherit the remotewebdriver from my BaseTest class so all my tests in another class can inherit the webdriver. Currently I only have it implemented in my 2nd class, I can do this quite easily if I am creating the tests locally, but we're utilizing a tool "CrossBrowserTesting" in order to scale our tests. Anyone have any ideas how this would look syntactically?
My attempts to inherit it from the BaseTest class haven't been panning out. It's not the same syntax i'm used to. The documentation is different from what I have provided as well.
Class 1
public class BaseTest {
public static String CBUsername = ABCD1;
public static String CBAuthkey = HIJK1;
public static String OS = "Windows 10";
public static String Build = "3";
public static String Browser = "Chrome";
public static String BrowserVersion = "73x64";
public static String Resolution = "1366x768";
public static String RecordVideo = "True";
public static String RecordNetwork = "False";
}
Class 2
#Test
public void ExampleTest throws MalformedURLException, UnirestException {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("name", "Dashboard"); // Set Name To Test Name
caps.setCapability("build", Build); // Set Build To Version Of Release
caps.setCapability("browserName", Browser); //Custom
caps.setCapability("version", BrowserVersion); //Custom
caps.setCapability("platform", OS); //Custom
caps.setCapability("screenResolution", Resolution); //Custom
caps.setCapability("record_video", RecordVideo); //Custom
caps.setCapability("record_network", RecordNetwork); //Custom
RemoteWebDriver driver = new RemoteWebDriver(new URL("http://" + CBUsername + ":" + CBAuthkey +"#hub.crossbrowsertesting.com:80/wd/hub"), caps);
try {
/* Set testScore to fail in-case an error is discovered at runtime. */
myTest.testScore = "fail";
/*
* Enter Code Here
*
*/
/* if we get to this point, then all the assertions have passed. */
myTest.testScore = "pass";
}
catch(AssertionError ae) {
String snapshotHash = myTest.takeSnapshot((driver).getSessionId().toString());
myTest.setDescription((driver).getSessionId().toString(), snapshotHash, ae.toString());
myTest.testScore = "fail";
}
finally {
System.out.println("Test complete: " + myTest.testScore);
// here we make an api call to actually send the score
myTest.setScore((driver).getSessionId().toString(), myTest.testScore);
// and quit the driver
driver.quit();
}
}
public JsonNode setScore(String seleniumTestId, String score) throws UnirestException {
/* Mark a Selenium test as Pass/Fail */
String username = CBUsername; /* Your username */
String authkey = CBAuthkey; /* Your authkey */
HttpResponse<JsonNode> response = Unirest.put("http://crossbrowsertesting.com/api/v3/selenium/{seleniumTestId}")
.basicAuth(username, authkey)
.routeParam("seleniumTestId", seleniumTestId)
.field("action","set_score")
.field("score", score)
.asJson();
return response.getBody();
}
String takeSnapshot(String seleniumTestId) throws UnirestException {
/*
* Takes a snapshot of the screen for the specified test.
* The output of this function can be used as a parameter for setDescription()
*/
String username = CBUsername; /* Your username */
String authkey = CBAuthkey; /* Your authkey */
HttpResponse<JsonNode> response = Unirest.post("http://crossbrowsertesting.com/api/v3/selenium/{seleniumTestId}/snapshots")
.basicAuth(username, authkey)
.routeParam("seleniumTestId", seleniumTestId)
.asJson();
// grab out the snapshot "hash" from the response
String snapshotHash = (String) response.getBody().getObject().get("hash");
return snapshotHash;
}
public JsonNode setDescription(String seleniumTestId, String snapshotHash, String description) throws UnirestException{
/*
* sets the description for the given seleniemTestId and snapshotHash
*/
String username = CBUsername; /* Your username */
String authkey = CBAuthkey; /* Your authkey */
HttpResponse<JsonNode> response = Unirest.put("http://crossbrowsertesting.com/api/v3/selenium/{seleniumTestId}/snapshots/{snapshotHash}")
.basicAuth(username, authkey)
.routeParam("seleniumTestId", seleniumTestId)
.routeParam("snapshotHash", snapshotHash)
.field("description", description)
.asJson();
return response.getBody();
}
}
}
Found a solution that might help others with a similar question
java.lang.NullPointerException Selenium 2 classes
public class PP_Main {
private static RemoteWebDriver driver;
private static String homeUrl;
//...
#BeforeClass
public static void setUp() throws Exception {
// ...
cap.setPlatform(Platform.ANY);
driver = new RemoteWebDriver(new
URL("http://51.19.210.111:5555/wd/hub"), cap);
// ...
}

Can i send information to testrail for selenium when my test runs its course

I am trying to send my tests to testrail from selenium but im not using an assert to end the test, i just want it to pass if it runs to completion? Is this possible? Also is there any examples of how this working in the code? I currently have:
public class login_errors extends ConditionsWebDriverFactory {
public static String TEST_RUN_ID = "R1713";
public static String TESTRAIL_USERNAME = "f2009#hotmail.com";
public static String TESTRAIL_PASSWORD = "Password100";
public static String RAILS_ENGINE_URL = "https://testdec.testrail.com/";
public static final int TEST_CASE_PASSED_STATUS = 1;
public static final int TEST_CASE_FAILED_STATUS = 5;
#Test
public void login_errors() throws IOException, APIException {
Header header = new Header();
header.guest_select_login();
Pages.Login login = new Pages.Login();
login.login_with_empty_fields();
login.login_with_invalid_email();
login.email_or_password_incorrect();
login.login_open_and_close();
login_errors.addResultForTestCase("T65013",TEST_CASE_PASSED_STATUS," ");
}
public static void addResultForTestCase(String testCaseId, int status,
String error) throws IOException, APIException {
String testRunId = TEST_RUN_ID;
APIClient client = new APIClient(RAILS_ENGINE_URL);
client.setUser(TESTRAIL_USERNAME);
client.setPassword(TESTRAIL_PASSWORD);
Map data = new HashMap();
data.put("status_id", status);
data.put("comment", "Test Executed - Status updated automatically from Selenium test automation.");
client.sendPost("add_result_for_case/"+testRunId+"/"+testCaseId+"",data );
}
}
I am getting a 401 status from this code.
Simply place the addResultForTestCase method at the end of the run. Ensure the Test CASE is used rather than the run id. You are currently using the incorrect ID

How to send my test results from selenium to testrail

I am having trouble sending my test results from selenium to testrail. I cant seem to figure it out using the paperwork provided. I am currently using this:
public class login_errors extends ConditionsWebDriverFactory {
public static String TEST_RUN_ID = "R1713";
public static String TESTRAIL_USERNAME = "testemai9#hotmail.com";
public static String TESTRAIL_PASSWORD = "Password1";
public static String RAILS_ENGINE_URL = "https://testproj.testrail.com/";
public static final int TEST_CASE_PASSED_STATUS = 1;
public static final int TEST_CASE_FAILED_STATUS = 5;
#Test
public void login_errors() throws IOException, APIException {
Header header = new Header();
header.guest_select_login();
Pages.Login login = new Pages.Login();
login.login_with_empty_fields();
login.login_with_invalid_email();
login.email_or_password_incorrect();
login.login_open_and_close();
login_errors.addResultForTestCase(TEST_RUN_ID,TEST_CASE_PASSED_STATUS," ");
}
public static void addResultForTestCase(String testCaseId, int status,
String error) throws IOException, APIException {
String testRunId = TEST_RUN_ID;
APIClient client = new APIClient(RAILS_ENGINE_URL);
client.setUser(TESTRAIL_USERNAME);
client.setPassword(TESTRAIL_PASSWORD);
Map data = new HashMap();
data.put("status_id", status);
data.put("comment", "Test Executed - Status updated automatically from Selenium test automation.");
client.sendPost("add_result_for_case/"+testRunId+"/"+testCaseId+"",data );
}
}
But i keep getting the following exception:
com.gurock.testrail.APIException: TestRail API returned HTTP
401("Authentication failed: invalid or missing user/password or
session cookie.")
Can anybody help me on the exact way this should be done out in java? I am not sure I am doing it correctly.
I'm using my own custom made API for testrail, but it is all based on same thing.
But looking to official gurrock,
documentation
First You need to add "testrail/" at the end of Your URL endpoint,
APIClient client = new APIClient("http://<server>/testrail/");
client.setUser("..");
client.setPassword("..");
Should be like this:
public static String RAILS_ENGINE_URL ="https://testproj.testrail.com/testrail/";
Second thing what I found out is that You're sending test run id in variable for testcase ID, this is not same.
And another thing is that test case ID shouldn't be with anything in front just pure number, not like "R123" but "123"
And Your method should than accept one more parameter, testRunId
public static void addResultForTestCase(String testRunId, String testCaseId, int status,String error) throws IOException, APIException {
String testRunId = TEST_RUN_ID;
APIClient client = new APIClient(RAILS_ENGINE_URL);
client.setUser(TESTRAIL_USERNAME);
client.setPassword(TESTRAIL_PASSWORD);
Map data = new HashMap();
data.put("status_id", status);
data.put("comment", "Test Executed - Status updated automatically from Selenium test automation.");
client.sendPost("add_result_for_case/"+testRunId+"/"+testCaseId+"",data );
}
And another thing is that You have to have created testrun, so You can have Yourself your testrun ID, like pic bellow:
And than test case ID is different from testrun id.

Using AWS Java's SDKs, how can I terminate the CloudFormation stack of the current instance?

Uses on-line decomentation I come up with the following code to terminate the current EC2 Instance:
public class Ec2Utility {
static private final String LOCAL_META_DATA_ENDPOINT = "http://169.254.169.254/latest/meta-data/";
static private final String LOCAL_INSTANCE_ID_SERVICE = "instance-id";
static public void terminateMe() throws Exception {
TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest().withInstanceIds(getInstanceId());
AmazonEC2 ec2 = new AmazonEC2Client();
ec2.terminateInstances(terminateRequest);
}
static public String getInstanceId() throws Exception {
//SimpleRestClient, is an internal wrapper on http client.
SimpleRestClient client = new SimpleRestClient(LOCAL_META_DATA_ENDPOINT);
HttpResponse response = client.makeRequest(METHOD.GET, LOCAL_INSTANCE_ID_SERVICE);
return IOUtils.toString(response.getEntity().getContent(), "UTF-8");
}
}
My issue is that my EC2 instance is under an AutoScalingGroup which is under a CloudFormationStack, that is because of my organisation deployment standards though this single EC2 is all there is there for this feature.
So, I want to terminate the entire CloudFormationStack from the JavaSDK, keep in mind, I don't have the CloudFormation Stack Name in advance as I didn't have the EC2 Instance Id so I will have to get it from the code using the API calls.
How can I do that, if I can do it?
you should be able to use the deleteStack method from cloud formation sdk
DeleteStackRequest request = new DeleteStackRequest();
request.setStackName(<stack_name_to_be_deleted>);
AmazonCloudFormationClient client = new AmazonCloudFormationClient (<credentials>);
client.deleteStack(request);
If you don't have the stack name, you should be able to retrieve from the Tag of your instance
DescribeInstancesRequest request =new DescribeInstancesRequest();
request.setInstanceIds(instancesList);
DescribeInstancesResult disresult = ec2.describeInstances(request);
List <Reservation> list = disresult.getReservations();
for (Reservation res:list){
List <Instance> instancelist = res.getInstances();
for (Instance instance:instancelist){
List <Tag> tags = instance.getTags();
for (Tag tag:tags){
if (tag.getKey().equals("aws:cloudformation:stack-name")) {
tag.getValue(); // name of the stack
}
}
At the end I've achieved the desired behaviour using the set of the following util functions I wrote:
/**
* Delete the CloudFormationStack with the given name.
*
* #param stackName
* #throws Exception
*/
static public void deleteCloudFormationStack(String stackName) throws Exception {
AmazonCloudFormationClient client = new AmazonCloudFormationClient();
DeleteStackRequest deleteStackRequest = new DeleteStackRequest().withStackName("");
client.deleteStack(deleteStackRequest);
}
static public String getCloudFormationStackName() throws Exception {
AmazonEC2 ec2 = new AmazonEC2Client();
String instanceId = getInstanceId();
List<Tag> tags = getEc2Tags(ec2, instanceId);
for (Tag t : tags) {
if (t.getKey().equalsIgnoreCase(TAG_KEY_STACK_NAME)) {
return t.getValue();
}
}
throw new Exception("Couldn't find stack name for instanceId:" + instanceId);
}
static private List<Tag> getEc2Tags(AmazonEC2 ec2, String instanceId) throws Exception {
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest().withInstanceIds(instanceId);
DescribeInstancesResult describeInstances = ec2.describeInstances(describeInstancesRequest);
List<Reservation> reservations = describeInstances.getReservations();
if (reservations.isEmpty()) {
throw new Exception("DescribeInstances didn't returned reservation for instanceId:" + instanceId);
}
List<Instance> instances = reservations.get(0).getInstances();
if (instances.isEmpty()) {
throw new Exception("DescribeInstances didn't returned instance for instanceId:" + instanceId);
}
return instances.get(0).getTags();
}
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// Example of usage from the code:
deleteCloudFormationStack(getCloudFormationStackName());
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Categories