I am trying to validate some text files. In the front end i am using JTextarea, The below method is called on every time the user enter 'Enter' key. If the file is too big,say 5000 lines and if the user enters many times 'Enter' key then, i am getting unexpected results, like even if the line is valid, it shows it as invalid.
Is there any thing to do with sleep, should i have to increase the sleep time or something else has to be done? Any ideas will be helpful
private TreeSet validate(int curLine, TreeSet errorSet) {
int increment = 0;
int nextLine = 0;
if (curLine == lines.length || errorSet.size() != 0) {
return errorSet;
} else {
String line = lines[curLine];
//validation starts. After validation, line is incremented as per the requirements
increment = 1 //As per requirement. Depends on validation results of the line
if (increment > 0) {
try{
Thread.currentThread().sleep(100);
}catch(Exception ex){
System.out.println(ex);
}
nextLine = (curLine + increment);
validate(nextLine, errorSet);
}
}
return errorSet;
}
I wouldnt look at making the sleep time any longer/shorter. Instead, I would consider doing a better time at marshalling the trigger to validate. Is there any reason to allow the input of a validation request while one is in progress? if not, i would look at blocking the call to validate while a current process is still not complete.
If you think that multiple validations should be able to occur in tandem, I would then look to the creation of a thread pool for these actions. Testing my determine how many threads can concurrently run, and therefore determine the size of your threadpool. At this point, system memory may also play an important point, so you may want to look at those statistics while testing as well.
Related
I am automating a test, and there are some steps where I need to repeat the 'Enter' key many times, so I am trying to create a loop where 'Enter' is pressed until an object becomes available, or visible.
I already tried quite a few different ways to do it, but it never works, normally the while statement or the if statement breaks without the condition being broken.
On the following example, I am creating object x and object y. I want to repeat y until I get to a window where x is available.
Also here are a few of my failed attempts.
TestObject x = findTestObject('path/1')
TestObject y = findTestObject('path/2')
while (true) {
WebUI.click(y)
if (WebUI.verifyElementPresent) break
}
//
//while (WebUI.verifyElementNotPresent(x, 10)) {
// WebUI.click(y)
//}
//while(true) {
// WebUI.click(y)
// if(WebUI.verifyElementVisible(x))
// WebUI.click(y)
//}
Example of what I am trying to avoid.
WebUI.click(y)
WebUI.click(y)
WebUI.click(y)
WebUI.setText(x, '1')
and there are some steps where I need to repeat the 'Enter' key many times, so I am trying to create a loop where 'Enter' is pressed until an object becomes available, or visible
It sounds like that field that "Enter" is being pressed on, is a search field, and that "object becoming available or visible" is a search result...
As for your retry logic, take a look at my answer on the Katalon Studio forum:
public class ActionHandler {
public static void HandleRetryableAction(Closure onAction, Closure onDone, long timeOut) {
long startTime = System.currentTimeSeconds();
while (System.currentTimeSeconds() < startTime + timeOut) {
try {
onDone(true, onAction());
return;
} catch (Exception ex) {
onDone(false, ex);
}
}
}
}
You should use this custom keyword like this:
ActionHandler.HandleRetryableAction({
WebUI.sendKeys(findTestObject('path/2'), // you should REALLY name this something better...something more meaningful...
Keys.ENTER.toString());
final TestObject firstSearchResult = findTestObject('path/1'); // again, fix the naming please!!
// we're waiting on search result to **disappear**, in order to squash any flakiness that comes from the next step...
WebUI.waitForElementNotPresent(firstSearchResult,
1,
FailureHandling.OPTIONAL);
return WebUI.waitForElementPresent(firstSearchResult,
5);
}, { boolean success, _ ->
if (!success) {
// take additional actions, such as refreshing the page, clicking some refresh widget, ...
}
},
15, // I set it to 3 times the wait time specified by Mate Mrse, for good measure
)
Take note of three things here...
1.) It's WebUI.sendKeys() to...well...send the keys. Also, the String argument is the stringification of org.openqa.selenium.Keys.ENTER .
2.) We are using the WebUI.waitForElementPresent() here. This is built-in keyword.
3.) I don't see any action we're taking if the result is NOT present after Enter, except spamming Enter. You should spell out what we should do in that case.
In the absence of any onRetry logic, I think your idea to use loop, and my idea to use ActionHandler, is overkill.
Please respond back with your full use case here, and maybe some screenshots of or link to the AUT itself, and I can adjust this answer to that!
You can use WebUI.verifyElementPresent() method like this (Note: you are missing the parenthesis in your example. Also, timeout is required):
condition = true
while (condition) {
WebUI.click(y)
if (WebUI.verifyElementPresent(x, 5)) {
condition = false
}
}
WebUI.setText(x, '1')
In Java/Android, is there a way to check whether the currently executing line of code is executing on a background thread or not?
I have a lil' program I'm conjuring up that has finally reached the full-spaghetti stage... this was intentional, you see, because this way... if a competitor gets their hands on the code, and they "open the hood," after looking at it for more than 20 seconds, their hair will catch on fire and they'll run away screaming... but now even I am getting confused and I need to check for this condition somehow.
Exhibit-A:
// can be called from 1,067 places... some of which are background threads.
public void startDoingAFunDance(String caller, int wobbleIntensity, int spineAngle, int feetSeparationInInches) {
if (!validCallersForFunDance.contains(caller)) {
Log.i("XXX", "Caller not allowed.");
return;
}
boolean wasCalledFromBackgroundThread = // ? < what to put here > ?
Log.i("XXX", "Was startDoingAFunDance() called from a background thread? And the answer is: " + wasCalledFromBackgroundThread);
// classified
}
An easy way to know it might be the following
boolean wasCalledFromBackgroundThread = (Thread.currentThread().getId() != 1);
background threads doesn't have id 1 (UI thread has).
I am learning java and so far I have created a password check using if statements. However I inserted my working String check into a while loop and added Thread.sleep(3000); for a 3 second delay, however once I completed that my GUI just keeps lagging and freezing on one page as if the button was pressed. Can somebody please show me how to make a working example of a code with a String check and after a certain amount of tries a delay to stop the user from trying again?
(here is what I have:)
//var declaration
boolean match = false;
String1 = "hi";
String2 = (I know this is not code but just to omit some code:) userInput
int time = 3000;
int attempt = 0;
//check
while(!match && attempt < (maximumTries+1)){
if(String1.equals(String2)){
System.out.print("match");
}
else if(attempt < 11){
attempt++;
System.out.println("Failed:" + attempt);
}
else{
attempt++;
System.out.println("Please try again later you have:" + attempt + "failed attempts");
try{
Thread.sleep(time);
}
catch(InterruptedException ex) {
Logger.getLogger(PasswordEntry.class.getName()).log(Level.SEVERE, null, ex);
}
time = time + 1000;//1 second more every time
}
}
your code is doing an infinite loop once the first attempt does not match.
in each of the iterations of your loop there is no change at all, aside from incrementing the counter. so the counter just increases forever (with some delays in between).
it seems the reasoning behind your code was that String2 got updated with user input inside the loop not outside. This way, on each iteration you would have a different String2 to compare against.
That's your issue, not the way you delay between attempts (that for sure can be improved in any case).
You should avoid using the Thread.sleep option since it completely freezes the main thread. You could also try creating another thread, which will be frozen and later in gives a callback to the main one. For example through a boolean variable. I'd also agree on the timer solution mentioned by BladeMight.
I'm trying to write a program to solve 2 puzzles who can't be solved independently from eachother, but have the same solution. My idea is that they both run in a seperate thread until they stop finding new pieces of information. Then they communicate what they have found by updating some shared state variables and continue if something was written by either one of them to the shared state.
I think a CyclicBarrier is the appropriate mechanism to use here. This is my code (which is running concurrently in 2 threads:
while (true) {
doSolvingLogicHere();
shareUpdates(); // this method updates the shared state variable and is synhronized
int count;
int updates = 0;
try {
count = writeBarrier.await();
updates = threadsUpdatedSomething;
if (count == 0) {
writeBarrier.reset();
threadsUpdatedSomething = 0; //'reset' the shared value
}
} catch (InterruptedException ex) {
Logger.getLogger(TwinSolver.class.getName()).log(Level.SEVERE, null, ex);
} catch (BrokenBarrierException ex) {
Logger.getLogger(TwinSolver.class.getName()).log(Level.SEVERE, null, ex);
}
if (updates == 0) { //no thread updated something
break;
} else { // at least one of the threads updated something, solving should continue in both threads
readUpdates();
}
}
ThreadsUpdatedSomething is a shared integer which is incremented in the 'ShareUpdates()' if anything at all was updated by the threads. When both threads didn't find anything new in the iteration, this means that they never will find anything new and the whole loop should be stopped for both threads. That's why I'm checking for it to be zero.
I would expect them to both stop when both threads did not write any new information in the shared state variables. But when running the program, one of the threads stop, while the other one keeps going. When debugging the program and setting breakpoints at 'readUpdates()' line, the program works as expected.
Is this the correct way for handling such a concurrent 'solving' loop? And in case it is correct, where is the error in my code?
Thanks for the help!
EDIT: Small mistake corrected. 'updates = threadsUpdatedSomething;' now at the correct place
As per API , await returns
the arrival index of the current thread, where index getParties() - 1 indicates the first to arrive and zero indicates the last to arrive
count = writeBarrier.await();
Being said , So only one of the Thread would receive the 0 . And only one thread would set the updates value to 0. Thats why the last arrived thread stopped and other one not stopped.
As per your statements , you need to stop the threads when you find both threads not updated the threadsUpdatedSomething. i assumed that time threadsUpdatedSomething would be zero.
If not you have to change the logic , some how to find when the condition has to be break and apply it
while (true) {
doSolvingLogicHere();
shareUpdates(); // this method updates the shared state variable and is synhronized
int count;
int updates = 0;
try {
writeBarrier.await();
if (threadsUpdatedSomething == 0) {
updates = threadsUpdatedSomething;
writeBarrier.reset();
threadsUpdatedSomething -= 2; //'reset' the counter by decrementing 2
}
} catch (InterruptedException ex) {
Logger.getLogger(TwinSolver.class.getName()).log(Level.SEVERE, null, ex);
} catch (BrokenBarrierException ex) {
Logger.getLogger(TwinSolver.class.getName()).log(Level.SEVERE, null, ex);
}
if (updates == 0) { //no thread updated something
break;
} else { // at least one of the threads updated something, solving should continue in both threads
readUpdates();
}
}
Also Don't forgot to set the break conditions in exception cases if required.
Me and a friend of mine are working on a game and basically, we have a hitbox set up where if our character hits it (a spider), the character loses health.
Because we are using a for loop, the inevitable happens, the player loses their health 1 by 1, but so fast the human eye can not see it. Therefore we need a timer, pause, or something for every x amount of time the player is hitting the spider. Here is our code:
if (ResetEntities.spiderObj.intersects(ResetEntities.blueCharacterObj)) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 100; i++) {
if (ResetEntities.blueHealth < 0) {
ResetEntities.blueHealth = 0;
Frame.blueHealthLabel.setText("Health: "
+ ResetEntities.blueHealth);
} else {
ResetEntities.getBlueHealth(ResetEntities.blueHealth - 1);
Frame.blueHealthLabel.setText("Health: "
+ ResetEntities.blueHealth);
}
}
}
In this code we have an if statement to check for intersection. I tried to sleep the script, (I realized 10 is incredibly fast, but 1000 lags horribly, so Thread#sleep isn't the way to go I imagine). Then we have a for statement to run 100 times (being the players health). Then we have an if seeing if the health goes below 0, set back to 0, so the player can't get negative health. If it's not below 0, we do the else and subtract 1 health. But as I said this runs too fast to see.
Any help?
The traditional way - and in my opinion best way - to do it is, to make the wounded character invulnerable until a specific point in time: When the character gets wounded, check the game-timeline (or if you dont have one then the current millis-count) then add a specific time eg 1 second (or the character-dependent recovery-time) and remember that timestamp in the character-object. A gametick that wants to wound a character first checks whether the character is still in hidden invulnerability. This is especially good because typically one doesn't really want multiple threads updating the game-state.
Use Timer for your background process' timing. And use javax.swing.SwingUtilities.invokeLater(Runnable) to update your GUI.
The question is unclear, but are you asking how you can stop the health from going down so quick? If so,this is what I would do:
You should have a int value invincibilityTime and set that to 100 once the player is hit, and then every time your game goes through the gameloop it decreases it by one. Put if(invincibilityTime <= 0) before the (ResetEntities.spiderObj.intersects(ResetEntities.blueCharacterObj)) to check if the invicibility period has expired.