import com.mathworks.mps.client.MATLABException;
import com.mathworks.mps.client.rest.MATLABParams;
import com.mathworks.mps.client.rest.MATLABResult;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class SyncExample{

	final static protected String CONTENT_TYPE = "application/x-google-protobuf";

    public static void main(String[] args){

        try{
			// URL of the MATLAB Production Server.
			String mpsBaseUrl = "http://localhost:9910";

            // Use the java.net package's URLConnection as HTTP Client in this example.		
            URL url;
            url = new URL(mpsBaseUrl + "/mymagic/mymagic");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            //Set Content-Type to protobuf.
            urlConnection.setRequestProperty("Content-Type", CONTENT_TYPE);

            // Make the initial POST request body with MATLABParams class.
            MATLABParams mlMakeBody = MATLABParams.newInstance(1, double[][].class, 2);

            // Write the MATLABParams object into the output stream of the HTTP request.
            OutputStream output = urlConnection.getOutputStream();
            output.write(mlMakeBody.getRequestBody());
            output.flush();

            // Parse the response body of the above HTTP request with methods from the MATLABResult class. 
			// The MATLABParams object created earlier is an input argument to the newInstance method.
            // If there is any error in MATLAB, call to getResult() throws a MATLABException which contains the error message
            // displayed in MATLAB.
            MATLABResult mlFinalResult1 = MATLABResult.newInstance(mlMakeBody, urlConnection.getInputStream());
            try{
                double[][] magicSq1 = (double[][]) mlFinalResult1.getResult();
                printResult(magicSq1);
            }catch(MATLABException e){
                e.printStackTrace();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    // Helper method to print out the magic square generated by MATLAB based on the input.
    private static void printResult(double[][] result) {
        for (double[] row : result) {
            for (double element : row) {
                System.out.print(element + " ");
            }
            System.out.println();
        }
    }


}