14
\$\begingroup\$

Description

This is a Java wrapper class for communicating with submissions written in other languages. If you decide to use this for a challenge, make your life easier and require submissions to post the command that runs it. If they can't run it from the command prompt, then you probably can't either.

TODO

There are a few things that I want to add but don't have time to finish right now. I'm also not sure how legal it is to redistribute some of the things that I want to redistribute.

  • Bundle a bunch of compilers for popular languages with the wrapper

Wrapper

// Your package line goes here

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

/**
 * Wraps a submission in a Java class.
 * @author Rainbolt
 */
public class Wrapper {

    private final String command;

    /**
     * Create a submission with the specified command.
     * @param command The command associated with the submission
     */
    public Wrapper(String command) {
        this.command = command;
    }

    /**
     * Invokes a submission and returns its response.
     * @param timeout The number of milliseconds allowed for the submission 
     * to respond
     * @return The output of the submission
     */
    public String getResponse(long timeout) {
        String response = "";

        try {
            // Start the process
            Process proc = Runtime.getRuntime().exec(command);

            // Attach a reader to the process
            BufferedReader pin = new BufferedReader(new InputStreamReader(proc.getInputStream()));

            // Allow the process to time out
            proc.waitFor(timeout, TimeUnit.MILLISECONDS);
            if (proc.isAlive())
                proc.destroy();

            // Read the output of the process
            while (pin.ready())
                response += pin.readLine() + System.lineSeparator();

        } catch (IOException | InterruptedException e) {
            System.out.println("An error occurred while attempted to get a response.");
        }

        return response;
    }
}

Typical Usage

In the example below, the program called SubmissionOne.py is saved to my C: drive. It will receive four arguments (everything after "python"). It has 1000 milliseconds to produce output before being forcibly terminated.

long timeout = 1000;
String command = "python C:\\SubmissionOne.py 123 324 345";
Wrapper wrapper = new Wrapper(command);
String response = wrapper.getResponse(timeout);
\$\endgroup\$
  • 4
    \$\begingroup\$ Oh look, some of this code found its way into my KOTH controller. How ever did that happen? (Thanks) \$\endgroup\$ – PhiNotPi Feb 10 '15 at 3:52

You must log in to answer this question.

Browse other questions tagged .