Block a function/button if they exceed maximum attempts - java

In my code, I'm only manage to direct user to the main page if they fail to authenticate themselves by exceeding the maximum attempts and apparently it is not effective if the user still can access to the authentication page and carry on with the attempts until they successfully authenticate themselves.
public void onAuthenticationFailed() {
//Add one to the number of attempts taken
attemptCount += 1;
if (attemptCount < maxAttemptAllowance) {
super.onAuthenticationFailed();
Toast.makeText(context, "Fingerprint Authentication Failed, Please Try Again", Toast.LENGTH_SHORT).show();
} else {
//here is where the system block user if they exceed the maximum attempts
Toast.makeText(context, "Exceed maximum attempts, try again in 5 minutes later", Toast.LENGTH_SHORT).show();
context.startActivity((new Intent(context, Main.class)));
}
}
So here is my question, is there is anyway i could block/restrict/disable a function but not the entire system for 5 minutes if the user exceed the maximum attempts.
Thanks in advance if u guys willing to suggest me a way as I really don't have the idea/logic for this problem

Store the condition in a SharedPreference along with the current time, so that even if the app is closed the value persists. That is a better option to do things like this. :)

Here is the working example of delay. It will hide(you can modify as you need) the button and shows the remaining time to appear it again.
private CountDownTimer delay_timer;
public void Delay_Timer(final int length){
int min;
Log.e("Delay timer"," Running ");
delay_timer = new CountDownTimer(length*1000, 1000) {
public void onTick(long millisUntilFinished) {
Log.e("Delay timer"," onTick "+"" +(millisUntilFinished / 1000)+ " Seconds remaining.");
if(delay!=null) delay.setText("Button will be Enabled in "+SecToMin(millisUntilFinished / 1000)+" sec.");
}
public void onFinish() {
enable_next();
}
};
try{
disable_next();
delay_timer.start();
}catch (Exception ex){
Log.e("Delay excpt"," "+ex.getMessage());
enable_next();
}
}
private String SecToMin(long totalSecs){
long hours = totalSecs / 3600;
long minutes = (totalSecs % 3600) / 60;
long seconds = totalSecs % 60;
String timeString = String.format("%02d:%02d:%02d", hours, minutes, seconds);
return timeString;
}
public void Stop_recording_timer(){
delay_timer.cancel();
}
private void enable_next(){
if(submit!=null){
delay.setText("");
submit.setVisibility(View.VISIBLE);
}
}
private void disable_next(){
if(submit!=null){
submit.setVisibility(View.INVISIBLE);
}
}
now when your attempt exceeds call.
if(exceeds){
Delay_Timer(time_in_secs);
}

Related

Repeating task with handler take more time than interval

I get my data from the server and have to update it every x seconds.
I do this using the Handler's postDelayed function.
private long mInterval = 10000;
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
try {
takeServerResponse(); //with vary duration
}catch (Exception e){
itsRunning = false;
} finally {
if(mHandler!=null) {
mHandler.postDelayed(mStatusChecker, mInterval);
}
}
}
};
Sometimes it may take more than X seconds to get new data.
What can I do in this situation?
If we need increase interval,how to determine when to do so?
You can calculate the duration time of your job and postDelayed your handler based on the duration time.
For example:
startTime = System.currentTimeMillis();
//your job
duration = System.currentTimeMillis() - startTime;
mInterval = mInterval - duration
your handler used to call the server response after 10 sec.But Its all depend own your internet speed to get the data from server that's the reason its take long time

How to set a timeout threshold to wait/sleep in java?

My task is simple to download a file from a url using selenium. I did till clicking on the download part. Now I want to wait till the file is downloaded.Fine. I use following and done.
do {
Thread.sleep(60000);
}
while ((downloadeBuild.length()/1024) < 138900);
Now challenge is for how much time do I wait ? Can I set some threshold ? I can think of is use a counter in do while and check till counter goes to 10 or something like that ? But any other way in Java ? As such I do not have any action to do till the file is downloaded.
How about this?
I think using TimeOut is not stable since there is no need to wait for a un-predictable downloading operation.
You can just turn to CompletableFuture using supplyAsync to do the downloading and use thenApply to do the processing/converting and retrieve the result by join as follows:
public class SimpleCompletableFuture {
public static void main(String... args) {
testDownload();
}
private static void testDownload() {
CompletableFuture future = CompletableFuture.supplyAsync(() -> downloadMock())
.thenApply(SimpleCompletableFuture::processDownloaded);
System.out.println(future.join());
}
private static String downloadMock() {
try {
Thread.sleep(new Random().nextInt() + 1000); // mock the downloading time;
} catch (InterruptedException ignored) {
ignored.printStackTrace();
}
return "Downloaded";
}
private static String processDownloaded(String fileMock) {
System.out.println("Processing " + fileMock);
System.out.println("Done!");
return "Processed";
}
}
You can use guava Stopwatch
Stopwatch stopwatch = Stopwatch.createStarted();
while ((downloadeBuild.length()/1024) < 138900 && topWatch.elapsed(TimeUnit.SECONDS) < 60);
If what you want is a time out practice, may be you can try code below:
long timeout = 10 * 60 * 1000;
long start = System.currentTimeMillis();
while(System.currentTimeMillis() - timeout <= start ){
//Not timeout yet, wait
}
//Time out, continue
It's quite common in java library.

Unable to find xPath SELENIUM JAVA

I have issue keep throw error of unable to find the xpath , as i set the loop for opening this xpath to insert data . Although i set the time wait for existance to 60secound but it still couldn't find it. I been trying alot method calling this by using title or status hence it still not working . Kindly advise
HTML :
91.14
CODE :
public void clickOnItemTax () {
By xPath = By.xpath("//a[contains(#href,'edit_total_amt')]");
this.sleep(3);
if (this.waitForExistence(xPath,60)) {
WebElement domLink = linkGet(xPath);
domLink.click();
} else {
JLog.fail("Unable to find a writable item taxdialog!");
}
}
-waitforExistence
public boolean waitForExistence(By by, int timeoutSeconds){
boolean exists = false;
Long polling_interval = (long) 250;
Long timeout = (long) timeoutSeconds * 1000; // in seconds
Long elapsed = (long) 0;
while (elapsed <= (timeout)) {
if (exists(by)) {
exists = true;
break;
}
try {
Thread.sleep(polling_interval);
} catch (InterruptedException e) {
JLog.warning(JLog.getStackTraceAsString(e));
break;
}
elapsed += polling_interval;
}
if (elapsed >= timeout) {
JLog.warning("waitForExistence waited for " + timeout/1000 + " seconds, but unable to find: " + by.toString());
}
return exists;
}
Thanks you
If it's an internal company webpage could I suggest that you give the an 'id' to make your life easier. If not you can do this. I'm always surprised by people writing their own wait method when you could use either the implicit or explicit wait time in Selenium.
The former is as follows, the only thing to be aware using this method is that when looking for an element it will always wait this long. It is however a much safer way to write your scripts looking for elements and doesn't bloat your code:
driver.manage().timeouts().implicitlyWait(6, TimeUnit.SECONDS);
if (driver.findElements(By.cssSelector("//*[#title=\"Override total tax amount\"]")).size()!=0)
{
driver.findElement(By.cssSelector("//*[#title=\"Override total tax amount\"]")).click();
}
else
{
JLog.fail("Unable to find a writable item taxdialog!");
}
The explicit way to do it would be as follows where 10 is your seconds:
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("//*[#title=\"Override total tax amount\"]")));
See the following link for more on this.
http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp

Convert Minutes to milliseconds Java/android

I am trying to convert given number of minutes into milliseconds.
For eg: 15mins or 20mins or 44mins should be converted to milliseconds programmatically.
I tried the below:
Calendar alarmCalendar = Calendar.getInstance();
alarmCalendar.set(Calendar.MINUTE,15);
long alarmTime = alarmCalendar.getTimeInMillis();
Log.e("Milli", "seconds"+alarmTime);
This doesn't give the right value? What is the best way to convert this?
TimeUnit.MINUTES.toMillis(yourMinutes)
see TimeUnit javadoc (android)
int minutes = 42;
long millis = minutes * 60 * 1000;
1 minute = 60000 millisecs.
int minutes = 1;
long milliseconds = minutes * 60000;
In Java 8+, use java.time.
java.time.Duration.ofMinutes(15).toMillis();
This answer is in reference to Android using Kotlin-
So if you are using MaterialTimePicker or TimePicker then you can get the hours and minutes values stored in the picker. Then use TimeUnit.HOURS.toMillis(picker.hour.toLong()) and TimeUnit.MINUTES.toMillis(picker.minutes.toLong()) to convert the received time to milliseconds and then add both the values to get the total time in Milliseconds which you can further use to store in Room Database for entering time and fetching when required.
Code for reference :
binding.timeStart.setOnClickListener {
openTimePicker()
picker.addOnPositiveButtonClickListener {
val h = picker.hour
val m = picker.minute
binding.timeStart.text = "$h:$m"
Timber.d("Start Time - $h: $m")
try {
val hour = TimeUnit.HOURS.toMillis(h.toLong())
val minute = TimeUnit.MINUTES.toMillis(m.toLong())
val totalTime = hour + minute
Timber.d("Hour - $hour, Minute - $minute, Total = $totalTime")
timeStart = totalTime
} catch (e: Exception) {
Timber.d("$e")
}
}
}
private fun openTimePicker() {
picker = MaterialTimePicker.Builder()
.setTimeFormat(TimeFormat.CLOCK_12H)
.setHour(12)
.setMinute(10)
.setTitleText("Set Start Time")
.build()
picker.show(childFragmentManager, "TAG")
}
This gives you the time in milli.
long currentTime = System.currentTimeMillis()
Handler handler = new Handler();
long waitTime = currentTime + (15*60*1000);
handler.postDelayed(new Runnable() {
public void run() {
// Alert or do something here.
}
}, waitTime);
This piece of code sleeps for 15 minutes and then executes the handler's run method. This way you can raise an alarm etc...

Countdown Timer in Android out of sync?

I am trying to make a countdown timer. I have came up with this code and initially I thought it worked. However when I run the app two things happen which I don't know how to fix...
It is out of sync, although it is the system Time and Date it said there was only 60 days left not 61 when I know it is 61!!
If I close the app and go back it resets the counters...
Any help with this would be appreciated, its not for anything particular just a personal project.
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView dateBx = (TextView) findViewById(R.id.textView1);
final TextView mTextField = (TextView) findViewById(R.id.mTextField);
final TextView minBx = (TextView) findViewById(R.id.minBx);
final TextView hourBx = (TextView) findViewById(R.id.hourBx);
//set todays date
DateFormat dateFormat1 = new SimpleDateFormat("dd/MM/yyyy");
Calendar cal1 = Calendar.getInstance();
//target date
DateFormat dateFormat2 = new SimpleDateFormat("dd/MM/yyyy");
Calendar cal2 = Calendar.getInstance();
cal2.set(2012,11,25);
//set maths
long time1 = cal1.getTimeInMillis();
long time2 = cal2.getTimeInMillis();
//difference variable
long diff = time2 - time1;
//equations
long diffSec = diff / 1000;
long dMins = diff / (60 * 1000);
long dHour = diff / (60 * 60 * 1000);
long dDay = diff / (24 * 60 * 60 * 1000);
new CountDownTimer(diff, 1000)
{
public void onTick(long millisUntilFinished)
{
mTextField.setText("Seconds remaining: " + millisUntilFinished / 1000);
dateBx.setText("Days remaining: " + millisUntilFinished / (24 * 60 * 60 * 1000));
minBx.setText("Minutes remaining: " + millisUntilFinished / (60 * 1000));
hourBx.setText("hours remaining: " + millisUntilFinished / (60 * 60 * 1000));
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
}
My code is a combination of some things that I learnt, in java and android, if you think of a better way of doing it all together then please let me know :)
Thanks
Android is not a Real Time OS so you can count that your Timer will run exactly every 1000 ms.
The most practical approach is, for each invocation, get the current date, get the target date, and recalculate the days/hours/minutes/seconds remaining (just as you did as the beginning of your app).
That would also solve your problem when closing/opening your app.
Here is an example how to sync the countDownTimer.
(as "onTick()" is not accurate according to Android)
The trick is to use only "onFinish()" and start a new timer using an Interface.
make a EXTENDED CLASS of countDownTimer:
public class oneShotTimer extends CountDownTimer {
TickListener invokeOnFinish; // Interface
public oneShotTimer (Context parent, int tickTime, TickListener contextPointer) {
super(tickTime, tickTime); // DEBUG: (/60)
....
}
At the OnFinish():
public void onFinish() {
invokeOnFinish.restartTimer();
}
public void onTick() {
Log.e("Timer", "Not suppose to happen");
}
Define an interface:
public interface TickListener {
public void restartTimer();
}
Now at the parent Object do the following:
1) Before starting the timer, get the time in MillinSecond -> "startTime";
2) Create the method for "TickListener::restartTimer" (I wrote psadu code)
#Override
public void restartTimer() {
// check if timer is done (make your own variable to monitor that)
// get the currentTime in MilliSecond
// calc TickTime , if we know that 30 tick are already counted
// there for ((30+1) x wantedTickTime) give us the target time for the next tick.
// TickTime = (31 x wantedTickTime) - (currentTime - startTime)
// for example, we want 1sec ticks, after 30 ticks it finished at 30.2 sec
// => (31 x 1) - (40.2 - 10) = 0.8 is the time we need to re start timer.
// re-run a new Timer with the new TickTime
}
Now let see how Java garbage collection will handle it.

Categories