2

What would the best way of going about creating a consumer-producer type relationship for harvesting and using Recaptcha v2 tokens for web scraping, I have a basic chrome extension in which to harvest these tokens which are then submitted to my java application through a locally hosted web server.

The issue I have is their tokens are only valid for 110s so they would need to be invalidated after this time to make sure they are not used, I would also like consumer threads to consume a token as soon as one becomes available if they need one, any suggestions in this area would be very helpful.

  • Consider the use of `Thread.sleep() // Probably bad` `java.util.Timer` and `javax.swing.Timer` – FailingCoder Oct 24 '19 at 20:47
  • @FailingCoder so declare and initialize the string then have a timer after it which when it ends sets the string to null, makes sense would you have any idea about setting it the null after being called –  Oct 24 '19 at 20:57
  • @SDJ has a much better example, check their link. – FailingCoder Oct 24 '19 at 20:58
  • Can you just start a timer when the page loads? And when they submit their input, check how much time has passed on the timer. Then automatically flag as invalid if your time limit as been passed – RobOhRob Oct 24 '19 at 21:17

2 Answers2

0

You may try Guava CacheBuilder

For instance;

initialize token store;

final Cache<String, String> tokens = CacheBuilder.newBuilder()
            .expireAfterWrite(100, TimeUnit.SECONDS)
            .build();

put some tokens;

tokens.put("TOKEN_1", "TOKEN_1");
tokens.put("TOKEN_2", "TOKEN_2");

remove a token after use;

synchronized (tokens) {
        tokens.getIfPresent("USED_TOKEN");
        tokens.invalidate("USED_TOKEN");
    }

They will be removed from cache after 100 seconds even if they are not used

Abdullah Gürsu
  • 3,010
  • 2
  • 17
  • 12
  • I'll give that a try that looks like the best option as they are just removed all together –  Oct 24 '19 at 22:12
  • [my code](https://imgur.com/gallery/aCSlhIu) how would you recommend best implementing that into my code that pulls the tokens from my clipboard (it deletes the first one incase it is old) –  Oct 25 '19 at 08:40
0

Another way is to use core java classes and lambdas.

    AtomicReference<String> myToken = new AtomicReference<>();
    ScheduledFuture future;
    ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);

Elsewhere in your code you would see if it was null when you need it and get another if necessary.

    String tokenValue = myToken.getAndSet(null);
    if (tokenValue == null) {
        tokenValue = "anothertokenvalue";
        myToken.set(tokenValue);
        future = exec.schedule(() -> myToken.set(null), 100, TimeUnit.SECONDS);
    } else {
        if (future != null) {
            future.cancel(true);
        }
    }
fedup
  • 1,209
  • 11
  • 26