Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added utility to execute functions within a time limit #44

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/main/java/io/github/pixee/security/ExecuteWithTimeout.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package io.github.pixee.security;

import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
* Holds utilities for executing methods and functions within a timeout.
*/
public class ExecuteWithTimeout{


/**
* Tries to execute a given {@link Callable} within a given timeout in milliseconds. Returns the result if successful, otherwise throws a {@link RuntimeException}.
*/
public static <E> E executeWithTimeout(final Callable<E> action, final int timeout) {
Future<E> maybeResult = Executors.newSingleThreadExecutor().submit(action);
try {
return maybeResult.get(timeout, TimeUnit.MILLISECONDS);
} catch (Exception e) {
throw new RuntimeException("Failed to execute within time limit.");
}
}
}
36 changes: 36 additions & 0 deletions src/test/java/io/github/pixee/security/ExecuteWithTimeoutTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package io.github.pixee.security;

import org.junit.jupiter.api.Test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertThrows;

final class ExecuteWithTimeoutTest {

@Test
void it_executes_within_timeout_and_returns(){
Pattern pat = Pattern.compile("string");
String input = "some very long string";
Matcher matcher = pat.matcher(input);
boolean result = ExecuteWithTimeout.executeWithTimeout(() -> matcher.find(), 5000);
assertThat(result, is(equalTo(true)));
}

@Test
void it_throws_exception_due_to_timeout(){
Pattern pat = Pattern.compile("string");
String input = "some very long string";
Matcher matcher = pat.matcher(input);
RuntimeException exception = assertThrows(
RuntimeException.class,
() -> ExecuteWithTimeout.executeWithTimeout(() -> matcher.find(), 0)
);
assertThat(exception.getMessage(), is(equalTo("Failed to execute within time limit.")));
}

}
Loading