Info :
I get fieldXpath from a config file, and it is "//input[#id='signin_password']"
HTML :
<li><input type="password" name="signin[password]" id="signin_password" /></li>
WORKS : (but not always)
Gets in the catch ...
public void doAction(WebDriver driver) throws TestException {
try {
WebElement el = driver.findElement(By.xpath(fieldXpath));
el.clear();
el.sendKeys(fieldValue);
} catch (Exception e) {
throw new TestException(this.getClass().getSimpleName() + ": problem while doing action : " + toString());
}
}
Does a solution that makes this code work with XPath?
I found the problem... : selenium WebDriver StaleElementReferenceException
*This may be caused because the page isn't loaded completely when the code starts or changes when the code is executed. You can either try to wait a little longer for the element or catch the StaleReferenceException and try again finding the div and the span.*
My code : (call these functions before each field)
/**
* Handle StaleElementReferenceException
* #param elementXpath
* #param timeToWaitInSec
*/
public void staleElementHandleByXpath(String elementXpath, int timeToWaitInSec) {
int count = 0;
while (count < 10) {
try {
WebElement slipperyElement = driver.findElement(By.xpath(elementXpath));
if (slipperyElement.isDisplayed()) {
slipperyElement.click(); // may throw StaleElementReferenceException
}
count = count + 10;
} catch (StaleElementReferenceException e) {
count = count + 1; // try again
} catch (ElementNotVisibleException e) {
count = count + 10; // get out
} catch (Exception e) {
count = count + 10; // get out
} finally {
// wait X sec before doing the action
driver.manage().timeouts().implicitlyWait(timeToWaitInSec, TimeUnit.SECONDS);
}
}
}
/**
* Wait till the document is really ready
* #param js
* #param timeToWaitInSec
*/
public void waiTillDocumentReadyStateComplete(JavascriptExecutor js, int timeToWaitInSec) {
Boolean ready = false;
int count = 0;
while (!ready && count < 10) {
ready = (Boolean) js.executeScript("return document.readyState == 'complete';");
// wait X sec before doing the action
driver.manage().timeouts().implicitlyWait(timeToWaitInSec, TimeUnit.SECONDS);
count = count + 1;
}
}
Use single ' quotes instead of ". So
String fieldXpath = "//input[#id='signin_password']";
Related
When i used the listed method to see whether an element is visible on the page, I get an exception stating that its unable to locate an element using the specified locator.
Any ideas, has anyone faced this issue before or even have a better method?
public boolean isElementPresentByWebElement(WebElement element) {
Wait<WebDriver> fluentWait = new FluentWait<WebDriver>(driver).withTimeout(15, TimeUnit.SECONDS)
.pollingEvery(1, TimeUnit.SECONDS).ignoring(NoSuchElementException.class);
for (int i = 0; i < 2; i++) {
try {
fluentWait.until(ExpectedConditions.visibilityOf(element));
System.out.println("Element is visible: " + element.toString());
return true;
} catch (Exception e) {
System.out.println(
"Unable to locate the element: " + element.toString() + ", Exception: " + e.toString());
throw (e);
}
}
return false;
}
I think your code is overly complicated for what you are trying to do. There is a built in class, ExpectedConditions, that will do what you want. You are also looping over the wait which is unnecessary. I would suggest that you pass in a locator (By) instead of a WebElement. It will expand your ability to use this function because you won't have to find the element before using the function.
public boolean isElementPresentByLocator(By locator)
{
try
{
new WebDriverWait(driver, 15).until(ExpectedConditions.visibilityOfElementLocated(locator));
System.out.println("Element is visible: " + locator.toString());
return true;
}
catch (TimeoutException e)
{
System.out.println("Unable to locate the element: " + locator.toString() + ", Exception: " + e.toString());
return false;
}
}
The code below is more of a direct translation and simplification of your code.
public boolean isElementPresentByWebElement(WebElement element)
{
try
{
new WebDriverWait(driver, 15).until(ExpectedConditions.visibilityOf(element));
System.out.println("Element is visible: " + element.toString());
return true;
}
catch (TimeoutException e)
{
System.out.println("Unable to locate the element: " + element.toString() + ", Exception: " + e.toString());
return false;
}
}
Updated :
try using following :
int waitCounter = 0;
public static void WaitUntilVisible(WebDriver driver, WebElement element) throws InterruptedException, IOException {
try {
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOf(elementToBeClicked));
if (!elementToBeClicked.isDisplayed()) {
System.out.println("Element not visible yet. waiting some more for " + element);
if (waitCounter < 3) {
waitCounter++;
WaitUntilVisible(element);
}
waitCounter = 0;
}
} catch (Exception e)
{
System.out.println("Handling exception");
}
}
I would like to change the color (background) from one picture to the background which comes from another picture.
Here is my code but it doesn´t work 100 %.
Here is my current output:
http://www.bilder-upload.eu/upload/48a6b6-1471634776.jpg
This are the images:
Original:
https://github.com/vincentclee/csci1302-software_development/blob/master/p1_green_screen/submission/sagar.jpg?raw=true
New background:
https://github.com/vincentclee/csci1302-software_development/blob/master/p1_green_screen/submission/india.jpg?raw=true
public class StartGreenScreen2 {
public static void main(String[] args) throws IOException {
String inputFile = "/Users/testGreenscreen/sagar.jpg";
String backgroundFile = "/Users/testGreenscreen/india.jpg";
exceptions(inputFile, backgroundFile, ".jpg", "green");
}
/**
* The exceptions method accepts a String array argument. This method
* handles exceptions that might bring up.
*
* #param args
* Contains parameters for program execution.
* #throws IOException
* For catching file problems.
*/
public static void exceptions(String inputFile, String backgroundFile, String outputFileType, String color) throws IOException {
// Creates 7 boolean variables, all of which have to be true for the
// colorChanger & colorWriter to execute.
boolean[] bool = new boolean[6];
// args[0] try & catch statements
try {
new FileReader(inputFile);
bool[0] = true;
} catch (FileNotFoundException e) {
System.out.println("Input file for color swap not found.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("No input file specified.");
} catch (Exception e) {
System.out.println("There is a problem with the inputfile.");
}
// args[1] try & catch statements
try {
new FileReader(backgroundFile);
bool[1] = true;
} catch (FileNotFoundException e) {
System.out.println("Input File not Found");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("No input file specified.");
} catch (Exception e) {
System.out.println("There is a problem with the inputfile.");
}
// args[2] try & catch statements
try {
if (outputFileType.contains("."))
bool[2] = true;
else
System.out.println("Outfile name invalid.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Output file not specified.");
} catch (Exception e) {
System.out.println("There is a problem with the outputfile.");
}
// args[3] try & catch statements
try {
if (inputFile.endsWith(".png") && backgroundFile.endsWith(".png") && outputFileType.equalsIgnoreCase(".png")) {
bool[3] = true;
} else if (inputFile.endsWith(".jpg") && backgroundFile.endsWith(".jpg") && outputFileType.equalsIgnoreCase(".jpg")) {
bool[3] = true;
} else
System.out.println("The extension of all input files do not match!");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Extension not specified.");
} catch (Exception e) {
System.out.println("There is a problem with the extension.");
}
// args[4] try & catch statements
try {
if (color.equalsIgnoreCase("green") || color.equalsIgnoreCase("white")
|| color.equalsIgnoreCase("auto"))
bool[4] = true;
else
System.out.println("The spedified color is not valid.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Color of replacement not specified.");
} catch (Exception e) {
System.out.println("There is a problem with the color of replacement.");
}
// Checks the dimensions of both the input and output image for same
// dimensions.
if (bool[0] && bool[1] && bool[2] && bool[3] && bool[4]) {
BufferedImage imageIn = ImageIO.read(new File(inputFile));
BufferedImage imageOut = ImageIO.read(new File(backgroundFile));
if (imageIn.getWidth() == imageOut.getWidth() && imageIn.getHeight() == imageOut.getHeight())
bool[5] = true;
else
System.out.println("The imgaes are not the same dimensions.");
}
// All arguments and dimensions have to be true for this to execute.
// Just to be safe, this has a general exception built in.
try {
if (bool[0] && bool[1] && bool[2] && bool[3] && bool[4] && bool[5])
// colorWriter(colorChanger(inputFile), backgroundFile, color);
colorWriter(colorChanger(inputFile,backgroundFile, color), outputFileType) ;
else
System.out.println("Program Terminated.");
} catch (Exception e) {
System.out.println("General Program Failure");
}
}
/**
* The color Changer method accepts a String array argument. This method
* changes the colors in the picture.
*
* #param args
* Contains parameters for program execution.
* #return imageIn BufferedImage stream for output
* #throws IOException
* For catching file problems.
*/
public static BufferedImage colorChanger(String normalFile, String backgroundFile, String color) throws IOException {
// Open file for replacement through Buffered Image stream.
BufferedImage imageIn = ImageIO.read(new File(normalFile));
// Open file background through Buffered Image stream.
BufferedImage imageOut = ImageIO.read(new File(backgroundFile));
// Array to store pixel information for calculation on extra credit
int[][] pixels = new int[imageIn.getHeight()][imageIn.getWidth()];
// Determines each pixel color and stores it into a 2D array to a
// corresponding location.
for (int col = 0; col < imageIn.getWidth(); col++) {
for (int row = 0; row < imageIn.getHeight(); row++) {
pixels[row][col] = imageIn.getRGB(col, row);
}
}
// Array to store different colors and their pixel counts.
int[][] colors = new int[10000][2];
colors[0][0] = pixels[0][0]; // Sets color value at position (0,0) to
// first array.
// Gets color information and stores it in a array, then it checks the
// array for color, and adds count.
// If the color does not exists, it goes down to a empty space, and
// creates a new entry, and sets one for count.
for (int col = 0; col < imageIn.getWidth(); col++) {
for (int row = 0; row < imageIn.getHeight(); row++) {
boolean bool = true;
int counter = 0;
for (int i = 0; i < colors.length; i++) {
if (pixels[row][col] == colors[i][0]) {
colors[i][1]++;
bool = false;
}
if (colors[i][0] == 0) {
counter = i;
break;
}
}
if (bool) {
colors[counter][0] = pixels[row][col];
colors[counter][1]++;
}
}
}
// Prints out array of color, and number of hits greater than 10.
System.out.println("Top Colors:");
for (int row = 0; row < colors.length; row++) {
if (colors[row][0] != 0 && colors[row][1] > 10)
System.out.println(colors[row][0] + " " + colors[row][1]);
}
// Determine's the color with the highest pixel count.
int high = colors[0][1];
int backgroundColor = colors[0][0];
for (int row = 0; row < colors.length; row++) {
if (colors[row][1] > high) {
backgroundColor = colors[row][0];
high = colors[row][1];
}
}
System.out.println("Color: " + backgroundColor + " Count: " + high);
// Override for args[4] color selector
if (color.equalsIgnoreCase("green")) {
backgroundColor = -16711935;
}
if (color.equalsIgnoreCase("white")) {
backgroundColor = -1;
}
// Color Changer
// If the pixel on the image to be changed is the same as the color to
// be changed, it changes the color.
// There is also a 50 point tolerance.
for (int col = 0; col < imageIn.getWidth(); col++) {
for (int row = 0; row < imageIn.getHeight(); row++) {
if (imageIn.getRGB(col, row) > (backgroundColor - 8388608)
&& imageIn.getRGB(col, row) < (backgroundColor + 8388608))
imageIn.setRGB(col, row, imageOut.getRGB(col, row));
}
}
return imageIn;
}
/**
* The colorWriter method accepts a BufferedImage stream, and a String array
* argument.
*
* #param imageIn
* A BufferedImage stream for inputImage.
* #param args
* Contains parameters for program execution.
* #throws IOException
* For catching file problems.
*/
public static void colorWriter(BufferedImage imageIn, String ouputPath) throws IOException {
// Generates a *.extension String.
String outputFile = ouputPath + ".jpg";
String testFile = "/Users/test.jpg";
// Writes output File
ImageIO.write(imageIn, "jpg", new File(testFile));
}
How can I solve this? Or does anybody has an idea to change the code?
You lost informations by JPEG compression, better use PNG.
Not all pixels in your picture have same green color in background.
Not replaced green pixels
Your tolerance check isn't good, better use square deviation.
fairly complex code but it's a very simple issue.
I have a thread, this is its run method:
public void run() //gets pages and writes to them
{ // i printed the pageId of every process to check they are running at the same time and competing for resources
for(ProcessCycle currentCycle : processCycles.getProcessCycles())
{
Long[] longArray = new Long[currentCycle.getPages().size()];
try {
Page<byte[]>[] newPages = mmu.getPages(currentCycle.getPages().toArray(longArray));
for(int i = 0; i < newPages.length; i++)
{
MMULogger.getInstance().write("GP:P" + id + " " + currentCycle.getPages().get(i) + " " + Arrays.toString(currentCycle.getData().get(i)), Level.INFO);
}
List<byte[]> currentPageData = currentCycle.getData();
System.out.println("process id " + id);
for(int i = 0; i < newPages.length;i++)
{
byte[] currentData = currentPageData.get(i);
newPages[i].setContent(currentData);
}
Thread.sleep(currentCycle.getSleepMs());
} catch (ClassNotFoundException | IOException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
don't bother reading all of it. just notice that after the mmu.getpages there is a for loop.
While a process is inside the for loop, i want to lock access to mmu.getpages for all other threads. synchronized is no good since my original process is no longer in mmu, but in the for loop, and reentrantlock might be a good idea but I'm unfamiliar with the syntax and ran into some issues.
long story short - how do i make all other threads wait while some thread is inside the for loop after mmu.getpages?
Usually I chose an approach like this:
private Object lock = new Object();
public void run() //gets pages and writes to them
{ // i printed the pageId of every process to check they are running at the same time and competing for resources
for(ProcessCycle currentCycle : processCycles.getProcessCycles())
{
Long[] longArray = new Long[currentCycle.getPages().size()];
try {
synchrnonized(lock) {
Page<byte[]>[] newPages = mmu.getPages(currentCycle.getPages().toArray(longArray));
for(int i = 0; i < newPages.length; i++)
{
MMULogger.getInstance().write("GP:P" + id + " " + currentCycle.getPages().get(i) + " " + Arrays.toString(currentCycle.getData().get(i)), Level.INFO);
}
}
List<byte[]> currentPageData = currentCycle.getData();
System.out.println("process id " + id);
for(int i = 0; i < newPages.length;i++)
{
byte[] currentData = currentPageData.get(i);
newPages[i].setContent(currentData);
}
Thread.sleep(currentCycle.getSleepMs());
} catch (ClassNotFoundException | IOException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Not sure if there is a better way. This will only work as expected when all threads share the same instance of this object, otherwise you have to make lock a static member variable.
In my opinion a ReadWriteLock might be a best approach.
Something like this:
public class MmuClass {
private ReadWriteLock blockGetPages = new ReentrantReadWriteLock();
public byte [] getPages(...) {
try{
blockGetPages.readLock().lock();
// ...
// ...
// ...
return result;
finally{
blockGetPages.readLock().unlock();
}
}
public void lockAccessToGetPages(){
blockGetPages.writeLock().lock();
}
public void unlockAccessToGetPages(){
blockGetPages.writeLock().unlock();
}
}
and
Page<byte[]>[] newPages = mmu.getPages(currentCycle.getPages().toArray(longArray));
try{
mmu.lockAccessToGetPages();
for(int i = 0; i < newPages.length; i++) {
MMULogger.getInstance().write("GP:P" + id + " " + currentCycle.getPages().get(i) + " " + Arrays.toString(currentCycle.getData().get(i)), Level.INFO);
}
} finally{
mmu.unlockAccessToGetPages();
}
In this solutions all "readers" can simultaneously call getPages(), the access is blocked after calling lockAccessToGetPages() and unblocked after calling unlockAccessToGetPages(). If one thread locks the object in write mode, only this thread has access to the method. If some thread tries to lock it in write mode, must wait until all readers, which are currently "inside" the metod, finish their fork and leave the method.
I am trying to write a program where the participant communicates with the program (I/O) via a console. Trick is, the console is part of a GUI, because I need the program to run off of a executable jar file. I append text with a scrollable text field, like so
textArea.append(printChar);
I give the method a String to work with, and it uses a nested for loop to take it, char by char, and append each Char (using string.substring()).
My problem is that it freezes up the entire time its supposed to be printing, then just displays it all. I don't know why, because I tested it using System.out.print, and it worked exactly as I wanted. So something is different about appending and printing. Any ideas?
Also, I am using Thread.Sleep(100) for my wait time.
public void actionPerformed(ActionEvent evt) {
if (!preforming){
preforming = true;
String input = textField.getText(); //Text from Input
textArea.append(dungeon.name + ": " + input + newline); //Add "text" to bottom of console
String[] output = dungeon.action(input);
//print everything in array output, char by char, with 2-3 seconds after each
for (int i = 0; i < output.length; i++){
String printThis = output[i];
if (printThis.length() > 0){
for (int j = 0; j < printThis.length(); j++){
String printChar = printThis.substring(j, j+1);
textArea.append(printChar);
//System.out.print(printChar);
try{
Thread.sleep(5);
} catch (InterruptedException e) {
System.out.print("Error ");
}
/*try { //useless
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
textArea.append("" + newline);
}
//cleaning up input bar
textField.setText("");
textField.selectAll();
//Make sure the new text is visible, even if there
//was a selection in the text area.
textArea.setCaretPosition(textArea.getDocument().getLength());
preforming = false;
}
}
I've edited my answer as you are showing more of your codes. Since, there is an outer loop in your code, I just included it inside the run method of timer in this new edit. And also I don't have the code for the dungeon so I just temporarily replace it with constant values so the program can run in my test.
public void actionPerformed(ActionEvent evt) {
java.util.Timer timer = new java.util.Timer();
timer.schedule(new java.util.TimerTask() {
public void run() {
if (!preforming){
preforming = true;
String newline = "\n";
String dungeonName = "Star Light";
String input = textField.getText(); //Text from Input
textArea.append(dungeonName + ": " + input + newline); //Add "text" to bottom of console
String[] output = {
"Twinkle twinkle little star.",
"How I wonder what you are.",
"Up above the world so high."
};
//print everything in array output, char by char, with 2-3 seconds after each
for (int i = 0; i < output.length; i++){
String printThis = output[i];
if (printThis.length() > 0){
for (int j = 0; j < printThis.length(); j++){
String printChar = printThis.substring(j, j+1);
textArea.append(printChar);
//System.out.print(printChar);
try{
Thread.sleep(25);
} catch (InterruptedException e) {
System.out.print("Error ");
}
/*try { //useless
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
textArea.append("" + newline);
}
//cleaning up input bar
textField.setText("");
textField.selectAll();
//Make sure the new text is visible, even if there
//was a selection in the text area.
textArea.setCaretPosition(textArea.getDocument().getLength());
preforming = false;
}
}
}, 1);
}
I am looking for possible methods that can increase download speed and improve cpu, memory performance. Currently I am downloading file in segments and transferring data using java nio transferFrom function.
public void startDownload() {
threadService.execute(() -> {
double currentBytes = bytesDone.doubleValue();
//Download each segment independently.
for (int i = 0; i < segments; i++) {
if (intialState[i] != -1) {
threadService.execute(new Segment((i * sizeOfEachSegment)
+ intialState[i], (i + 1) * sizeOfEachSegment, i));
}
}
if (intialState[segments] != -1) {
threadService.execute(new Segment((segments * sizeOfEachSegment)
+ intialState[segments], sizeofFile, segments));
}
// Keep saving states of threads. And updating speed.
while (bytesDone.get() < sizeofFile) {
for (int i = 0; i < 1; i++) {
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
System.out.println("thread interupted while sleeping");
}
System.out.println(speed
= (int) ((bytesDone.doubleValue() - currentBytes) / 5120));
currentBytes = bytesDone.doubleValue();
avgSpeed[0] += speed;
avgSpeed[1]++;
}
states.saveState(stateArray, currentState);
}
// Download Complete.
try {
fileChannel.close();
file.close();
} catch (IOException ex) {
System.out.println("failed to close file");
}
currentState.set(2);
states.saveState(stateArray, currentState);
System.out.println("Alhamdullilah Done :)");
System.out.println("Average Speed : " + avgSpeed[0] / avgSpeed[1]);
});
}
public class Segment implements Runnable {
long start;
long end;
long delta;
int name;
public Segment(long start, long end, int name) {
this.start = start;
this.end = end;
this.name = name;
}
#Override
public void run() {
try {
HttpGet get = new HttpGet(uri);
// Range header for defining which segment of file we want to receive.
String byteRange = start + "-" + end;
get.setHeader("Range", "bytes=" + byteRange);
try (CloseableHttpResponse response = client.execute(get)) {
ReadableByteChannel inputChannel = Channels.newChannel(
response.getEntity().getContent());
while (start < end && currentState.get() == 1) {
delta = fileChannel.transferFrom(inputChannel, start, 8192);
start += delta;
bytesDone.addAndGet(delta);
stateArray.set(name, start);
}
stateArray.set(name, -1);
}
System.out.println("Thread done: " + name);
} catch (IOException ex) {
System.out.println("thread " + name + " failed to download");
}
}
}
This implementation gives 400+ kb/s but Internet Download Manager downloads same file at 500+ kb/s.
Are there any resources I can reuse(I noticed every connection initially takes time to reach its maximum speed so is there any way i can reuse the same thread to download the next portion of file as soon as it complete downloading previous)?