Java – Get the h2o MOJO model in the Spring boot app (zip file)

Get the h2o MOJO model in the Spring boot app (zip file)… here is a solution to the problem.

Get the h2o MOJO model in the Spring boot app (zip file)

I’m writing a Spring boot application (java class) that calls the H2o predict method in another java class.

I’ve tested this java class independently, and if it’s the same place as calling java, I can read the MOJO model and I can make predictions.

With the Spring boot application, this time the jar generated by my maven project compilation cannot read the zip.
I read the MOJO zip file using the standard way provided by Wrapper h2o.

EasyPredictModelWrapper model = new EasyPredictModelWrapper(MojoModel.load("DRF_model_python_1504558159175_1.zip"));

My Maven project structure is as follows:

enter image description here

The jar generated by the Spring boot app also contains the zip: shown below

enter image description here

I don’t understand why it gives me the error that the MOJO zip file cannot be found (which is an IOexception).

File DRF_model_python_1504558159175_1.zip cannot be found.

I think the solution could be:
1. Add something to the Maven pom file so that the generated jar knows where to get the model.
Either
2. If the MojoModel.load method accepts a file path instead of just a file name. But I don’t think it will work.

Any ideas?

Solution

You need to change how you load the MOJO

zip file in your project, and instead you need to load the MOJO file as a stream from the resource. Follow this example where you can see how to put MOJOs into the resources folder and then call addMOJOsFromJARResource to include MOJOs.

Item: https://github.com/h2oai/h2o-tutorials/tree/f67765bc6c68c2058d4b2786d1bbc627d3b70539/tutorials/hive_udf_template/hive_udf_mojo_template

  1. MOJO zip is stored in src/main/resources/model
  2. You need to reference the following h2o-genmodel class

“`

 import hex.genmodel.MojoReaderBackendFactory;
 import static hex.genmodel.MojoReaderBackendFactory.CachingStrategy;
 import hex.genmodel.MojoReaderBackend;
 import hex.genmodel.ModelMojoReader;
  1. This is the function that includes all MOJO.zip (yes, you can add multiple MOJOs) into your project

“`

  public void addMOJOsFromJARResource() {
      try {
        String[] mojo_names = this.getMOJONames();
        for (int i = 0; i < mojo_names.length; i++) {
            MojoReaderBackend reader =
                MojoReaderBackendFactory.createReaderBackend(
                  getClass().getResourceAsStream(
                     "/models/"+mojo_names[i]), 
                      MojoReaderBackendFactory.CachingStrategy.MEMORY);
            MojoModel model = ModelMojoReader.readFrom(reader);
            this.addModel(model);
        }
       } catch (Exception e) {
         e.printStackTrace();
        throw new RuntimeException();
        }
    }

“`
This will work.

Related Problems and Solutions