Trying to turn off warnings in console but failing - java

My IRC bot sends the statistics of a video when a YouTube link is posted to the channel. But I get warnings in a huge number and they annoy me and just clutter my console:
Sep 01, 2014 6:09:29 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
WARNUNG: CSS error: 'https://s.ytimg.com/yts/cssbin/www-core-vfl0pJopz.css' [1:41191] Fehler in Style-Regel. (Ungültiger Token "*". Erwartet wurde einer von: <EOF>, <S>, <IDENT>, "}", ";".)
Sep 01, 2014 6:09:29 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler warning
WARNUNG: CSS warning: 'https://s.ytimg.com/yts/cssbin/www-core-vfl0pJopz.css' [1:41191] Ignoriere die folgenden Deklarationen in dieser Regel.
I'd like to turn them off, and have tried to add this code to my main method:
java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);
But to no avail. I am using Selenium to get the results using this code:
String[] args = Utilities.toArgs(event.getMessage()); //this is the message sent, split by a space
String link = null;
boolean shortLink = false;
WebDriver driver = new HtmlUnitDriver();
String title = "No value";
String duration = "No value";
String views = "No value";
String likes = "No value";
String dislikes = "No value";
String date = "No value";
String uploader = "No value";
for(String s : args)
{
if(s.contains("www.youtube.com/watch"))
{
if(s.contains("v="))
link = "http://www.youtube.com/watch?v=" + s.split("v=")[1].substring(0, 11) + "/";
else
{
Utilities.chanMsg(event, "Couldn't find video id!"); //just sending a message to the channel
break;
}
}
else if(s.contains("http://youtu.be/"))
{
link = s;
shortLink = true;
break;
}
}
if(shortLink)
{
String videoId = link.split("/")[3];
link = "www.youtube.com/watch?v=" + videoId;
}
//if someone posts the link without a space between the link and the word before it
if(!link.startsWith("w"))
link = link.split(":")[1].substring(2);
//check that the link is really the link needed (main use is when someone posts a word directly after the link without a space inbetween)
if(link.length() != 35)
{
StringBuilder builder = new StringBuilder();
builder.append(link);
builder.delete(35, link.length());
link = builder.toString();
}
//make sure that the links starts with "http://"
if(!link.startsWith("http://"))
link = "http://" + link;
driver.get(link);
try
{
title = driver.findElement(By.xpath("//meta[#itemprop='name']")).getAttribute("content");
}
catch(NoSuchElementException e){}
try
{
duration = resolveDuration(driver);
}
catch(NoSuchElementException e){}
try
{
views = driver.findElement(By.xpath("//div[#class='watch-view-count']")).getText();
}
catch(NoSuchElementException e)
{
views = driver.findElement(By.xpath("//span[#class='watch-view-count yt-uix-hovercard-target']")).getText().split("Views")[0];
}
try
{
likes = driver.findElement(By.xpath("//button[#id='watch-like']/span[#class='yt-uix-button-content']")).getText();
}
catch(NoSuchElementException e){}
try
{
dislikes = driver.findElement(By.xpath("//button[#id='watch-dislike']/span[#class='yt-uix-button-content']")).getText();
}
catch(NoSuchElementException e){}
try
{
date = driver.findElement(By.xpath("//p[#id='watch-uploader-info']/strong")).getText().split("on")[1];
}
catch(NoSuchElementException e){}
try
{
uploader = driver.findElement(By.xpath("//div[#class='yt-user-info']/a")).getText();
}
catch(NoSuchElementException e){}
driver.close();
So how would I be able to suppress the warnings sent to the console?

You can handle this using Capabilities
Though these capabilities are browser specific.Say for firefox it would be like webdriver.log.driver. For more details you can refer the link below.
Desired Capabilities
More details on logging in Selenium Webdriver can be found here : Logging in Selenium
UPDATED : If you are using HtmlUnitDriver for which no browser is opened, You have to use your own logging system with proper configuration. You can go either for Log4j or SimpleLog library.
In case you use log4j, just add this line in a file commons-logging.properties
org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger
and keep the log4j.xml in the same folder where property file is kept.Normally the /src/main/resources: folder in case its a Maven Project.Then in log4j.xml you can configure your logging level as per your need.

Related

How to handle script failure due to server response time in Selenium Webdriver?

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")));

Restfb - Why when I fetch my admined groups the app throws OAuthException: (#200) Permissions error (code 200, subcode null)

I'm programming in Java and I'm trying to fetch all the Facebook groups which I am the admin.
Thus, I've created an app called "Secrets" in Facebook Graph API Explorer and
checked all the permissions when I generated my ACCESS TOKEN.
For my Java app I'm using the library: restfb-1.18.0
The weird thing is that I'm getting the list of my admined groups but then
the app throws the exception: OAuthException: (#200) Permissions error (code 200, subcode null)
I don't know why i get this error.
Here is my code snippet:
String accessTokenGraphApiExplorer = "...";
FacebookClient fbClient = new DefaultFacebookClient(accessTokenGraphApiExplorer,Version.VERSION_2_0);
int counter = 0;
final String MY_FEEDS_PROPERTY = "me/groups";
String param = "groups,name";
Connection<Group> result = fbClient.fetchConnection(MY_FEEDS_PROPERTY, Group.class, Parameter.with("fields", param));
try {
for (List<Group> groupPage : result) {
for (Group group : groupPage) {
System.out.println(group.getName());
counter++;
}
}
System.out.println("# of Groups I admin: " + counter);
}
catch (Exception e) {
System.out.println(e);
}
How can I fix it ?

Unable to handle alert using phantomJS in Java

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?

EWS Java how to find emails older than xx days and Delete all in one shot

I want to find items in a folder which are older than xx days and Delete all the items found in one shot.
I was able to find the items matching my criteria. here is my code.
import org.joda.time.DateTime;
int purgeDays = 14;
try {
ItemView view = new ItemView(Integer.MAX_VALUE);
Folder purgeFolder = Folder.bind(service, folderId);
// need to convert to get Mon Sep 12 16:31:27 CDT 2016
SearchFilter searchFilter = new SearchFilter.IsLessThanOrEqualTo(ItemSchema.DateTimeReceived, (DateTime.now().minusDays(purgeDays).toDate()));
FindItemsResults<Item> emailsToPurge = service.findItems(purgeFolder.getId(), searchFilter, view);
if (emailsToPurge != null && emailsToPurge.getItems() != null && emailsToPurge.getTotalCount() > 0 ) {
// want something to delete all items at once
emailsToPurge.deleteAll();
} else {
log.info("Found no emails to purge for Mailbox-"+ userName);
}
} catch (Exception e) {
log.error("Exception "+ e.getMessage());
}
Have a look at the deleteItems method on the ExchangeService class https://msdn.microsoft.com/en-us/library/microsoft.exchange.webservices.data.exchangeservice.deleteitems(v=exchg.80).aspx this allows you to send a batch DeleteItem request. I would suggest you page your deletes though at no more than 1000 items at a time else you may have issue with throttling and/or the requests timing out.

How to correctly use google alerts API with java

I'm learning to work with google alerts API.
I want to create an alerts from java code, and when I have alerts put them to my DB
My way:
I'm able to create an new google alert , that would send alerts to my gmail.
Read all the mails with java from my mail.
I parse them and put to my DB.
Is there a better way to do that ?
I saw that google can give me an XML rss , it would be much easier to parse , but I wasn't able to get the rss with java.
Thanks for any help.
Maybe it would be helpful :
Java code to create google alert:
public static void addAlertToUser(String userMail , String password , String query)
{
GAService service;
try {
service = new GAService(userMail, password);
service.doLogin();
Alert alert = new Alert();
alert.setSearchQuery(query);
alert.setHowOften(HowOften.AS_IT_HAPPENS);
//alert.setLanguage(Region.Israel);
//alert.setLanguage(Language.Hebrew);
alert.setHowMany(HowMany.ONLY_THE_BEST_RESULTS);
service.createAlert(alert);
} catch (Exception e) {
e.printStackTrace();
}
}
Code to read the alert from the Gmail:
public static void readGoogleAlretsEmail()
{
Hashtable<String , Alert[]> allAlerts = checkMail("myGmail#gmail.com", "12q3wa4esz");
for(String key : allAlerts.keySet())
{
System.out.println("Key : " + key + "\n");
Alert[] alerts = allAlerts.get(key);
for (int i = 0; i < alerts.length; i++)
{
Alert currentAlret = (Alert)alerts[i];
System.out.println(i + ". " + alerts[i]);
TextAnalysisResults results = TextAnalysis.getResults(currentAlret.title,currentAlret.content);
}
}
}

Categories