I am trying to get the web status for a given page. However when its a 404 error, the page does not return the status code, rather it throws and error.
int status= webClient.getPage("website").getWebResponse().getStatusCode();
System.out.println( status);
Any Ideas?
I am looking to see when sites time out, however for testing purposes I malformed the url of the desired website to see if I can even see a 404.
According to this
You can do this:
webclient.setThrowExceptionOnFailingStatusCode(False)
****EDIT ***
This does print out your status code:
WebClient webClient = new WebClient();
webClient.setThrowExceptionOnFailingStatusCode(false);
int status = webClient.getPage("http://google.co.uk/ffffff").getWebResponse()
.getStatusCode();
System.out.println(status);
Prints out 404 - your status code.
Alternatively, you can continue to allow the FailingHttpStatusCodeException to be thrown (true). Then within the catch clause get the error status code.
...
int status = 0;
Object page = null;
try {
page = webClient.getPage(webRequest);
webClient.close();
if (page instanceof UnexpectedPage) {
status = ((UnexpectedPage) page).getWebResponse().getStatusCode();
} else if (page instanceof HtmlPage) {
status = ((HtmlPage) page).getWebResponse().getStatusCode();
}
// do something else ...
} catch (FailingHttpStatusCodeException | IOException e) {
if (e instanceof FailingHttpStatusCodeException) {
status = ((FailingHttpStatusCodeException) e).getStatusCode();
}
// do something else ...
}
Related
I am trying to store multiple types of Records in Cosmo DB using batch operation. But I am getting 400 status in CosmoBatchResponse object and errorMessage is null. Internally , one item is giving 400 , all the other operations have a 424 status code (failed dependency). From this [document] https://learn.microsoft.com/en-us/rest/api/cosmos-db/http-status-codes-for-cosmosdb I can see there could be many reason of 400 , but if errorMessage is null then how to find what went wrong . Also , same msg is getting stored via create call ,facing issue while batch save only.
PartitionKey partitionKey = new PartitionKey("customerNo");
CosmosBatch batch = CosmosBatch.createCosmosBatch(partitionKey);
batch.createItemOperation(customer);
I have tried to store via create method only looping on CosmosItemOperation and it is getting stored.
CosmosBatchResponse response=paymentRepository.createBatch(cosmosBatch);
for(CosmosItemOperation itemOp:cosmosBatch.getOperations()) {
System.out.println(paymentRepository.create(itemOp.getItem(),""));// Here it is getting stored.
}
public CosmosBatchResponse createBatch(CosmosBatch cosmosBatch) {
CosmosBatchResponse response = null;
try {
response = container.executeCosmosBatch(cosmosBatch);
System.out.println(response.isSuccessStatusCode()); -- returns false
System.out.println(response.getErrorMessage()); -- returns null
return response;
} catch (final Exception e) {
int statusCode = CosmosUtils.getCosmosStatusCode(e);
if (CONFLICT_RESOURCE == statusCode) {
log.error(
"CosmosCreateDocumentException: Resource already exists for Document : {}",
response.getErrorMessage());
}
shouldRetryOnException(e);
log.error(
"CosmosCreateDocumentException for Document {} - {}, {}", cosmosBatch, e.getMessage(), e);
throw new GenericRepositoryException(e.getMessage(), e);
}
}
I am a beginner for Selenium Webdriver, I have written a script in Java to test a functionality, and it is working fine. Sometimes I faces an issue.
Suppose I just click on create button to create something (let suppose customer) and after this I need to do some work with a screen which comes after create successfully customer. Sometimes due to slow response from server, my script get failed due to search a DOM element which comes after create customer.
If response come with in predefined time in my code, no issue, if not come then script failed (it search a element which has not rendered yet).
1) click on button
try{
// let suppose creatButtonElement is the web element of Create Button.
createButtonElement.click();
}catch(Exception e){
throw new Exception("Unable To Click on element [ " + element + " ] , plz see screenshot [ UnableToClick_" + element);
}
Expecting: after click on create button my script is expecting success message for assertion.
I had faced this issue once but I had handled this manually. This will work if after click button loader is appearing. It waits for one minute.
Please use the following code to wait manually to get response of server. It check the visibility of loader to know the response each second.
public static void loading_wait() throws Throwable {
int i = 0;
int maxloopDependOnBrowser = 60;
int totalSecond=0;
boolean loadinImageTakingMuchTime=false;
try{
while (true) {
i++;
if( !(loaderDisplayed(APP_LoadingImage_xpath)) ){
totalSecond+=i;
break;
}
if (i > maxloopDependOnBrowser) {
totalSecond=maxloopDependOnBrowser + 1;
loadinImageTakingMuchTime=true;
break;
} else {
totalSecond=i;
Thread.sleep(1000);
}
}
Thread.sleep(1000);
if(loadinImageTakingMuchTime){
throw new Throwable();
}
}catch (Throwable t) {
throw new Exception("FAILED:>>> Loading image is taking too much time :>>"+Throwables.getStackTraceAsString(t));
}
}
XpathKey :- to find the loader element
public static boolean loaderDisplayed(String XpathKey) {
int i = 0;
try {
driver.manage().timeouts().implicitlyWait(5, TimeUnit.MILLISECONDS);
List<WebElement> elementList = getORObject_list(XpathKey/*, 0, 500*/);
for (Iterator<WebElement> iterator = elementList.iterator(); iterator.hasNext();) {
WebElement webElement = (WebElement) iterator.next();
if (webElement.isDisplayed()) {
i = 1;
break;
}
}
} catch (Throwable t) {
}
finally {
driver.manage().timeouts().implicitlyWait(Long.parseLong(1), TimeUnit.SECONDS);
}
if (i == 0) {
return
} else {
return true;
}
}
You can join waiting
WebDriverWait wait = new NWebDriverWait(driver, 10); //10 second
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("btn1")));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("btn1")));
wait.until(ExpectedConditions.elementToBeClickable(By.id("btn1")));
I have a Java code as below and when I am running through PhantomJs getting "Unsupported Command Exception" but it is working fine if I run through firefox and chrome:-
Note: With phantomJs we could able to execute till 3rd step in below code.I searched in many blogs but those answers didn't solve my problem.
1. cvvField.sendKeys(cvcData);
2. proceedToPayBtn.click();
3. Reporter.log("Card details are submitted from payment UI page");
4. Alert a1=driver.switchTo().alert();
5. Reporter.log("Alert with text:"+a1.getText());
6. a1.accept();
Here cvvField and proceedToPayBtn are WebElements and cvcData have value as "111".
Error log:-
org.openqa.selenium.UnsupportedCommandException: Invalid Command Method -
{"headers":{"Accept-Encoding":"gzip,deflate","Cache-Control":"no-cache","Connection":"Keep-Alive","Host":"localhost:30462","User-Agent":"Apache-HttpClient/4.5.1 (Java/1.8.0_101)"},"httpVersion":"1.1","method":"GET","url":"/alert_text","urlParsed":{"anchor":"","query":"","file":"alert_text","directory":"/","path":"/alert_text","relative":"
/alert_text","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/alert_text","queryKey":{},"chunks":["alert_text"]},"urlOriginal":"/session/9e392a50-ce79-11e6-b24a-2b12cf1ec4d6/alert_text"}
Command duration or timeout: 31 milliseconds
I have edited above code as below but same error is coming.Please suggest
if (driver instanceof PhantomJSDriver)
{
JavascriptExecutor je = (JavascriptExecutor) driver;
je.executeScript("window.alert = function(){};");
je.executeScript("window.confirm = function(){return true;};");
System.out.println("Alert has been handled");
} else {
Alert a1 = driver.switchTo().alert();
a1.accept();
}
I am getting "Alert has been handled" in output console but alert is not handled.
Some issue due to wait time can be the source of your problem
The code above can help to wait until element is visible (since the wait of ngWebDriver or Selenium Webdriver are not compatible with PhantomJS)
public static String waitJSResponse(PhantomJSDriver driver, String script) {
String ReturnedValue = null;
int sleeper = 10;
Boolean flag = false;
int timeOut = 30000;
int i = 0;
while ((!flag) & ((i*sleeper)<timeOut)) {
try {
Thread.sleep(sleeper);
ReturnedValue = (String) driver.executeScript(script);
} catch (Exception e) {
flag = false;
i++;
}
if (ReturnedValue != null) {
flag = true;
System.out.println("Overall wait time is : "+(i * sleeper)+" ms \n\r");
break;
}
}
return ReturnedValue;
}
This code will wait 10ms then verify that the element is visble, if there is an exception, it will loop again.
The returned value must be a text, an object or anything that is not null.
the script value must be your JS script to get the correct element.
Hope it work.
I tried the above code by:-
1.Creating a class "Test" and writing above method in it.
2.Above method is called by creating an object(TestObject) as
TestObject.waitJSResponse((PhantomJSDriver) driver, "window.confirm = function(){return true;};");
But ReturnedValue in
try
{
Thread.sleep(sleeper);
ReturnedValue = (String) driver.executeScript(script);
System.out.println(ReturnedValue);
}
returns null.So Can u please help with this?
I want to constract a telephone-caller inside my java application. For this pupose I used a JAIN-SIP library. After the first INVITE the system needs Proxy-Authentication. The second invite is conscructed with the help of "AuthenticationHelperImpl.class":https://gitorious.org/0xdroid/external_nist-sip/source/1e0f37693341071f316852c8e05a08deef2b7fc4:java/gov/nist/javax/sip/clientauthutils/AuthenticationHelperImpl.java#L311, includes Proxy-Authentication header and lloks like:
INVITE sip:+11111111111#fpbx.de;maddr=fpbx.de SIP/2.0
Call-ID: 1c609509a43b721ab11c396c1e6ea9e7#192.168.17.107
CSeq: 2 INVITE
From: "77735hk6iu" <sip:77735hk6iu#fpbx.de>
To: "+111111111111111" <sip:+11111111111#fpbx.de>
Via: SIP/2.0/UDP 192.168.17.107:34567;rport;branch=z9hG4bK-383337-5bc4fd6b7a616843fce9eaa243bcb10e
Max-Forwards: 70
Contact: <sip:77735hk6iu#192.168.17.107:5060>
Content-Type: application/sdp
Proxy-Authorization: Digest username="77735hk6iu",realm="fpbx.de",nonce="VLaIxVS2h5muPS30F2zLdXHjup6ELyen",uri="sip:+111111111111#fpbx.de:5060;maddr=fpbx.de",response="47ea578c6b01c99fd3ed2b41c60983df"
Content-Length: 61
v=0
o=- 130565705777141827 1 IN IP4 192.168.17.107
s=call
After that I receive at the beginning code 100 message ("your call is very important for us") followed with 408 code message ("Request Timeout").
What I did to imporve the situation:
tried different phone number formats: 004930208488480,
04930208488480, 049, 0049, sdfhajfkhsk. For all these numbers I
become the same combination on messages.
tried to use port in request uri
tried to remove maddr from request uri.
tried to fullfill the message body with codek settings.
to set and remove rport from via header
If you now what I'm doing wrong, please, help me.
Thank you in advance.
I think, Maybe your Proxy-Authorization header is wrong. Maybe you is miscalculated. I wanted to share my resolve.
authUser is your phoneNumber. (for example: 77735hk6iu )
authPass is your user's password.
msg is your invite request.(Headers !)
AccountManagerImpl accountManagerImp = new AccountManagerImpl(authUser, AuthPass);
AuthenticationHelperImpl authenticationHelperImpl = new AuthenticationHelperImpl(accountManagerImp);
try {
this.authentication = authenticationHelperImpl.handleChallenge(msg, (SIPClientTransaction)trans);
AuthenticationHelperImple.java Class :
public AuthorizationHeader handleChallenge(Response challenge, ClientTransaction challengedTransaction) throws SipException {
SIPRequest challengedRequest = ((SIPRequest) challengedTransaction.getRequest());
ListIterator authHeaders = null;
if (challenge.getStatusCode() == Response.UNAUTHORIZED) {
authHeaders = challenge.getHeaders(WWWAuthenticateHeader.NAME);
}
else {
if (challenge.getStatusCode() == Response.PROXY_AUTHENTICATION_REQUIRED) {
authHeaders = challenge.getHeaders(ProxyAuthenticateHeader.NAME);
}
else {
throw new IllegalArgumentException("Unexpected status code ");
}
}
if (authHeaders == null) {
throw new IllegalArgumentException("Could not find WWWAuthenticate or ProxyAuthenticate headers");
}
WWWAuthenticateHeader authHeader = null;
while (authHeaders.hasNext()) {
authHeader = (WWWAuthenticateHeader) authHeaders.next();
String realm = authHeader.getRealm();
this.uri = challengedRequest.getRequestURI();
this.requestMethod = challengedRequest.getMethod();
this.requestBody = (challengedRequest.getContent() == null) ? "" : new String(challengedRequest.getRawContent());
if (this.accountManager instanceof SecureAccountManager) {
UserCredentialHash credHash = ((SecureAccountManager) this.accountManager).getCredentialHash(challengedTransaction,
realm);
if (credHash == null) {
logger.logDebug("Could not find creds");
throw new SipException("Cannot find user creds for the given user name and realm");
}
this.authorizationHeader = this.getAuthorization(requestMethod, uri.toString(), requestBody, authHeader, credHash);
}
else {
UserCredentials userCreds = ((AccountManager) this.accountManager).getCredentials(challengedTransaction, realm);
if (userCreds == null) {
throw new SipException("Cannot find user creds for the given user name and realm");
}
// sipDomain = userCreds.getSipDomain();
// we haven't yet authenticated this realm since we were
// started.
this.authorizationHeader = this.getAuthorization(requestMethod, uri.toString(), requestBody, authHeader, userCreds);
}
}
return this.authorizationHeader;
}
getAuthorization function :
public AuthorizationHeader getAuthorization(String method,
String uri,
String requestBody,
WWWAuthenticateHeader authHeader,
UserCredentials userCredentials) throws SecurityException {
String response = null;
String qopList = authHeader.getQop();
String qop = (qopList != null) ? "auth" : null;
String nc_value = "00000001";
String cnonce = "xyz";
try {
response = MessageDigestAlgorithm.calculateResponse(authHeader.getAlgorithm(),
userCredentials.getUserName(), authHeader.getRealm(),userCredentials.getPassword(), authHeader.getNonce(), nc_value, // JvB added
cnonce, // JvB added
method, uri, requestBody, qop,logger);
}
catch (NullPointerException exc) {
throw new SecurityException("The received authenticate header was malformatted: " + exc.getMessage());
}
AuthorizationHeader authorization = null;
try {
if (authHeader instanceof ProxyAuthenticateHeader) {
if (this.headerFactory != null) {
authorization = headerFactory.createProxyAuthorizationHeader(authHeader.getScheme());
}
else {
authorization = new ProxyAuthorization();
authorization.setScheme(authHeader.getScheme());
}
}
else {
if (this.headerFactory != null) {
authorization = headerFactory.createAuthorizationHeader(authHeader.getScheme());
}
else {
authorization = new Authorization();
authorization.setScheme(authHeader.getScheme());
}
}
authorization.setUsername(userCredentials.getUserName());
authorization.setRealm(authHeader.getRealm());
authorization.setNonce(authHeader.getNonce());
authorization.setParameter("uri", uri);
authorization.setResponse(response);
if (authHeader.getAlgorithm() != null) {
authorization.setAlgorithm(authHeader.getAlgorithm());
}
if (authHeader.getOpaque() != null) {
authorization.setOpaque(authHeader.getOpaque());
}
// jvb added
if (qop != null) {
authorization.setQop(qop);
authorization.setCNonce(cnonce);
authorization.setNonceCount(Integer.parseInt(nc_value));
}
authorization.setResponse(response);
} catch (ParseException ex) {
throw new RuntimeException("Failed to create an authorization header!");
}
return authorization;
}
Finally, your this.authentication variable is ProxyAuthorizationHeader. You must put this.authentication in your INVITE message. And than you will sent SipMessage from transaction or dialog to JAIN-SIP stack.
Good Luck !
The problem was partly solved when a removed "maddr=fpbx.de" from request URI and from proxy-auth. uri
fpr this a used handleCahllenge method with boolean arguments:
inviteTid = authenticationHelper.handleChallenge(response, tid, sipProvider, 15, **true**);
But I still don't know how I can a acchieve sponaneous telephone number.
The 100 message is hop-by-hop, that is to say it just means the next hop got your request. Other messages will typically be end-to-end (so, if you got a 180 Ringing, that typically means the endpoint being called sent the 180). A 408 typically shows up when one of the hops sent the INVITE but never got a response (and your SIP stack might be generating that internally when it doesn't get a provisional response in a reasonable timeframe -- usually about 32 seconds with the default SIP timers).
I don't know your network setup, but there are several private IPs in that message (of the 192.168.x.x variety). If I had to guess, your first hop is sending the 100 back to the IP/port it received it from, but the next response is following the Via headers (as it should), and the hop after you isn't respecting the rport parameter, so the response is getting lost. Alternately, your NAT is poorly configured and is closing the hole it created for the INVITE too quickly.
If you have a proxy on the edge of your network that this message is going out, it is either putting bad Via headers on the message (possibly with the internal IP instead of the external IP) or it is sending the INVITE to the wrong place (causing it to never get a response), and the 408 is coming from it.
ResponsePacket theErrorResponse = pushedNotification.getResponse();I'm using javapns2.2 and trying to catch error-response packet from from apple's Enhanced notification format. When I send push notification (with invalid token for example) the code
Exception theProblem = pushedNotification.getException();
theProblem.printStackTrace();
outputs some error to the console, but
ResponsePacket theErrorResponse = pushedNotification.getResponse();
if (theErrorResponse != null && theErrorResponse.isErrorResponsePacket()) {
System.out.println(theErrorResponse.getMessage());
System.out.println(theErrorResponse.getStatus());
}
always returns null. How can I obtain status codes with getResponse()?
Here is a part of my code:
List<PushedNotification> notifications = Push.payload(payload, keystore, password, production, devices);
for (PushedNotification pushedNotification : notifications) {
if(pushedNotification.isSuccessful())
{
System.out.println(pushedNotification.getDevice().getToken());
}
else
{
System.out.println(pushedNotification.getDevice().getToken());
Exception theProblem = pushedNotification.getException();
theProblem.printStackTrace();
ResponsePacket theErrorResponse = pushedNotification.getResponse();
if (theErrorResponse != null && theErrorResponse.isErrorResponsePacket()) {
System.out.println(theErrorResponse.getMessage());
System.out.println(theErrorResponse.getStatus());
}
}
}
Thank you for your help
I figured it out.
getResponse() returns null because Exception mechanism is preventing the call to APNs to be more efficient. True errors are packed within Exception mechanism.
Everything is super explained at this link:
http://code.google.com/p/javapns/issues/detail?id=79&can=1