org.adminmap.core.rpc.Request.java Source code

Java tutorial

Introduction

Here is the source code for org.adminmap.core.rpc.Request.java

Source

package org.adminmap.core.rpc;

/**
 * Copyright 2013 Philip Koshy
    
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
    
 http://www.apache.org/licenses/LICENSE-2.0
    
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

import java.util.Arrays;
import java.lang.TypeNotPresentException;

import org.adminmap.core.utility.JSON;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Request extends JSONizer {

    private String method;
    private JSONArray params;

    public Request() {
        this.params = new JSONArray();
    }

    public Request(final String method) {
        this.method = method;
        this.params = new JSONArray();
    }

    // This function initializes this object via a json string representation
    @Override
    public void fromJSONString(final String json) {

        final JSONObject jsonObject = new JSONObject(json);

        this.method = jsonObject.getString("method");
        this.params = jsonObject.optJSONArray("params");

    } // end of fromJSONString()

    @Override
    public String toJSONString() {

        if (method == null || method.trim().isEmpty()) {
            throw new JSONException("The method name cannot be empty");
        }

        final JSONObject jsonObject = new JSONObject();
        jsonObject.put("method", method);

        if (params.length() != 0)
            jsonObject.put("params", params);

        return jsonObject.toString();
    }

    public void setMethodName(final String methodName) {
        this.method = methodName;
    }

    /** 
     * Add a parameter to the internal Request parameter array
     * 
     * @param classProperty the .class property of the object
     * @param parameter An instance of the parameter object
     * 
     */
    public <T> void addParameter(final Class<?> classProperty, final T parameter) {

        final Class<?> boxedClassProperty = JSON.getBoxedType(classProperty);
        final String className = boxedClassProperty.getName();

        if (!JSON.isSupportedType(boxedClassProperty))
            throw new RuntimeException("Unsupported type passed to addParameter(): " + className);

        final JSONObject jsonObject = new JSONObject();

        if (JSONizer.class.isInstance(parameter))
            jsonObject.put(className, ((JSONizer) parameter).toJSONObject());
        else if (boxedClassProperty == Boolean[].class || boxedClassProperty == Integer[].class
                || boxedClassProperty == Long[].class || boxedClassProperty == Double[].class
                || boxedClassProperty == String[].class) {
            @SuppressWarnings("unchecked")
            T[] parameters = (T[]) parameter;
            jsonObject.put(className, Arrays.asList(parameters));
        } else
            jsonObject.put(className, parameter);

        this.params.put(jsonObject);

    } // end of addParameter()

    public String getMethodName() {
        return this.method;
    }

    public int getParameterCount() {

        if (params == null)
            return 0;

        return params.length();
    }

    /**
     * Determines the class property that is encoded is our param array at the specified index
     * 
     * @param index
     * @return the class property
     * 
     */
    private Class<?> getParameterClassProperty(final int index) {

        final JSONObject jsonObject = params.getJSONObject(index);
        final String className = JSONObject.getNames(jsonObject)[0]; // The key is the class name
        Class<?> encodedClassProperty = null;
        try {
            encodedClassProperty = Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new TypeNotPresentException(className, e);
        }

        return encodedClassProperty;
    } // end of getParameterClassProperty()

    /**
     * This method returns an Object[] of the instantiated request parameters
     * 
     * @return the instantiated request parameters
     */

    public Object[] getParameters() {

        final int parameterCount = getParameterCount();
        final Object[] parameters = new Object[parameterCount];

        for (int index = 0; index < parameterCount; index++) {

            Class<?> classProperty = getParameterClassProperty(index);

            if (!JSON.isSupportedType(classProperty))
                throw new RuntimeException("Unsupported type passed to addParameter(): " + classProperty.getName());

            if (classProperty.getSuperclass().equals(JSONizer.class))
                parameters[index] = getObjectParameter(classProperty, index);
            else if (classProperty == Boolean.class)
                parameters[index] = JSON.getBoolean(params.getJSONObject(index));
            else if (classProperty == Boolean[].class)
                parameters[index] = JSON.getBooleanArray(params.getJSONObject(index));
            else if (classProperty == Integer.class)
                parameters[index] = JSON.getInteger(params.getJSONObject(index));
            else if (classProperty == Integer[].class)
                parameters[index] = JSON.getIntegerArray(params.getJSONObject(index));
            else if (classProperty == Long.class)
                parameters[index] = JSON.getLong(params.getJSONObject(index));
            else if (classProperty == Long[].class)
                parameters[index] = JSON.getLongArray(params.getJSONObject(index));
            else if (classProperty == Double.class)
                parameters[index] = JSON.getDouble(params.getJSONObject(index));
            else if (classProperty == Double[].class)
                parameters[index] = JSON.getDoubleArray(params.getJSONObject(index));
            else if (classProperty == String.class)
                parameters[index] = JSON.getString(params.getJSONObject(index));
            else if (classProperty == String[].class)
                parameters[index] = JSON.getStringArray(params.getJSONObject(index));

        } // end of for

        return parameters;

    } // end of getParameters()

    /**
     *  Prints a method prototype in the following format:
     *  <p>
     *  methodName(Type, Type, ...)
     */
    public void printPrototype() {

        if (method == null || method.trim().isEmpty()) {
            System.out.println("No method name specified in the request");
            return;
        }

        if (params == null || params.length() == 0) {
            System.out.println(method + "()");
            return;
        }

        System.out.print(method + "(");

        for (int i = 0; i < params.length(); i++) {

            final JSONObject parameters = params.getJSONObject(i);
            for (String className : JSONObject.getNames(parameters)) {

                Class<?> classProperty = null;
                try {
                    classProperty = Class.forName(className);
                } catch (ClassNotFoundException e) {
                    throw new TypeNotPresentException(className, e);
                }

                System.out.print(classProperty.getSimpleName());
                if (i < params.length() - 1)
                    System.out.print(", ");
            }
        } // end of for()

        System.out.println(")");

    } // end of printRequest()

    /**
     *  Get a parameter object that extends the org.adminmap.core.rpc.JSONizer class from the request object
     * @param classProperty
     * @param index The index of the parameter, starting from 0
     * @return Returns an instantiated object of type classProperty
     * @see org.adminmap.core.rpc.JSONizer
     */
    public <T> T getObjectParameter(Class<T> classProperty, int index) {

        final int parameterCount = getParameterCount();
        if (index < 0 || index > parameterCount)
            throw new IndexOutOfBoundsException("The index was out of bounds: " + index);

        // Determine the class property that is encoded is our param array at the specified index
        JSONObject jsonObject = params.getJSONObject(index);
        Class<?> encodedClassProperty = getParameterClassProperty(index);

        // Make sure it is the same class property that was provided to this function
        if (classProperty != encodedClassProperty)
            throw new IllegalArgumentException(
                    "The class specified does not match the class encoded in the json representation: "
                            + classProperty.getSimpleName() + " vs " + encodedClassProperty.getSimpleName());

        // Create a new instance of this class
        T parameterObject = null;
        try {
            parameterObject = (T) classProperty.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException("Could not instantiate the result object");
        }

        if (!JSONizer.class.isInstance(parameterObject))
            throw new IllegalArgumentException(
                    "The parameter object was not an instance of JSONizer: " + classProperty.getName());

        // Initialize and return the object using the json encoding
        ((JSONizer) parameterObject).fromJSONObject(jsonObject.getJSONObject(encodedClassProperty.getName()));

        return parameterObject;

    } // end of getParameter()

    public Boolean getBooleanParameter(final int index) {

        final int parameterCount = getParameterCount();
        if (index < 0 || index > parameterCount)
            throw new IndexOutOfBoundsException("The index was out of bounds: " + index);

        return JSON.getBoolean(params.getJSONObject(index));
    }

    public Boolean[] getBooleanArrayParameter(final int index) {

        final int parameterCount = getParameterCount();
        if (index < 0 || index > parameterCount)
            throw new IndexOutOfBoundsException("The index was out of bounds: " + index);

        return JSON.getBooleanArray(params.getJSONObject(index));
    }

    public Integer getIntegerParameter(final int index) {

        final int parameterCount = getParameterCount();
        if (index < 0 || index > parameterCount)
            throw new IndexOutOfBoundsException("The index was out of bounds: " + index);

        return JSON.getInteger(params.getJSONObject(index));

    }

    public Integer[] getIntegerArrayParameter(final int index) {

        final int parameterCount = getParameterCount();
        if (index < 0 || index > parameterCount)
            throw new IndexOutOfBoundsException("The index was out of bounds: " + index);

        return JSON.getIntegerArray(params.getJSONObject(index));
    }

    public Long getLongParameter(final int index) {

        final int parameterCount = getParameterCount();
        if (index < 0 || index > parameterCount)
            throw new IndexOutOfBoundsException("The index was out of bounds: " + index);

        return JSON.getLong(params.getJSONObject(index));
    }

    public Long[] getLongArrayParameter(final int index) {

        final int parameterCount = getParameterCount();
        if (index < 0 || index > parameterCount)
            throw new IndexOutOfBoundsException("The index was out of bounds: " + index);

        return JSON.getLongArray(params.getJSONObject(index));
    }

    public Double getDoubleParameter(final int index) {

        final int parameterCount = getParameterCount();
        if (index < 0 || index > parameterCount)
            throw new IndexOutOfBoundsException("The index was out of bounds: " + index);

        return JSON.getDouble(params.getJSONObject(index));
    }

    public Double[] getDoubleArrayParameter(final int index) {

        final int parameterCount = getParameterCount();
        if (index < 0 || index > parameterCount)
            throw new IndexOutOfBoundsException("The index was out of bounds: " + index);

        return JSON.getDoubleArray(params.getJSONObject(index));
    }

    public String getStringParameter(final int index) {

        final int parameterCount = getParameterCount();
        if (index < 0 || index > parameterCount)
            throw new IndexOutOfBoundsException("The index was out of bounds: " + index);

        return JSON.getString(params.getJSONObject(index));
    }

    public String[] getStringArrayParameter(final int index) {

        final int parameterCount = getParameterCount();
        if (index < 0 || index > parameterCount)
            throw new IndexOutOfBoundsException("The index was out of bounds: " + index);

        return JSON.getStringArray(params.getJSONObject(index));
    }

} // end of class Request