All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.algorithmia.development.Handler Maven / Gradle / Ivy

There is a newer version: 2.0.2
Show newest version
package com.algorithmia.development;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.stream.Stream;
import org.springframework.core.annotation.AnnotationUtils;


public class Handler {

    private AbstractAlgorithm implementation;
    private RequestHandler in;
    private ResponseHandler out = new ResponseHandler();


    public Handler(AbstractAlgorithm implementation) {
        this.implementation = implementation;
        Class inputClass = getInputClass(implementation);
        this.in = new RequestHandler<>(inputClass);
    }

    private void load() {
            implementation.load();
            System.out.println("PIPE_INIT_COMPLETE");
            System.out.flush();
        }


    private void execute() {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        Stream buffer = reader.lines();
        load();
        buffer.forEach((line) -> {
            INPUT input = in.processRequest(line);
            OUTPUT output = implementation.apply(input);
            out.writeToPipe(output);
        });
    }

    private Class getInputClass(AbstractAlgorithm algoClass) {
        Method[] methods = algoClass.getClass().getMethods();
        Class bestGuess = null;
        for (Method method : methods) {
            if (AnnotationUtils.findAnnotation(method, FindApply.class) != null) {
                bestGuess = (Class) method.getParameterTypes()[0];
                if (method.getReturnType() != Object.class) {
                    return bestGuess;
                }
            }
        }
        if (bestGuess != null) {
            return bestGuess;
        } else {
            throw new RuntimeException("Unable to find the 'public' method reference called " + "'apply'" + " in the provided class.");
        }
    }


    public void serve() {
        try {
            execute();
        } catch (RuntimeException e) {
            out.writeErrorToPipe(e);
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy