001/*
002 * (C) Copyright 2006-2013 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     bstefanescu
018 */
019package org.nuxeo.ecm.automation.core.impl;
020
021import java.lang.reflect.InvocationTargetException;
022import java.lang.reflect.Method;
023import java.util.Arrays;
024import java.util.Map;
025
026import org.apache.commons.logging.Log;
027import org.apache.commons.logging.LogFactory;
028import org.nuxeo.ecm.automation.OperationContext;
029import org.nuxeo.ecm.automation.OperationException;
030import org.nuxeo.ecm.automation.OperationType;
031import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
032import org.nuxeo.ecm.core.api.Blob;
033import org.nuxeo.ecm.core.api.Blobs;
034import org.nuxeo.ecm.core.api.DocumentModel;
035import org.nuxeo.ecm.core.api.DocumentModelList;
036import org.nuxeo.ecm.core.api.NuxeoException;
037
038/**
039 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
040 */
041public class InvokableMethod implements Comparable<InvokableMethod> {
042
043    protected static final Log log = LogFactory.getLog(InvokableMethod.class);
044
045    public static final int VOID_PRIORITY = 1;
046
047    public static final int ADAPTABLE_PRIORITY = 2;
048
049    public static final int ISTANCE_OF_PRIORITY = 3;
050
051    public static final int EXACT_MATCH_PRIORITY = 4;
052
053    // priorities from 1 to 16 are reserved for internal use.
054    public static final int USER_PRIORITY = 16;
055
056    protected OperationType op;
057
058    protected Method method;
059
060    protected Class<?> produce;
061
062    protected Class<?> consume;
063
064    protected int priority;
065
066    public InvokableMethod(OperationType op, Method method, OperationMethod anno) {
067        produce = method.getReturnType();
068        Class<?>[] p = method.getParameterTypes();
069        if (p.length > 1) {
070            throw new IllegalArgumentException("Operation method must accept at most one argument: " + method);
071        }
072        // if produce is Void => a control operation
073        // if (produce == Void.TYPE) {
074        // throw new IllegalArgumentException("Operation method must return a
075        // value: "+method);
076        // }
077        this.op = op;
078        this.method = method;
079        priority = anno.priority();
080        if (priority > 0) {
081            priority += USER_PRIORITY;
082        }
083        consume = p.length == 0 ? Void.TYPE : p[0];
084    }
085
086    public InvokableMethod(OperationType op, Method method) {
087        produce = method.getReturnType();
088        Class<?>[] p = method.getParameterTypes();
089        if (p.length > 1) {
090            throw new IllegalArgumentException("Operation method must accept at most one argument: " + method);
091        }
092        this.op = op;
093        this.method = method;
094        String inputType = this.op.getInputType();
095        if (inputType != null) {
096            switch (inputType) {
097            case "document":
098                consume = DocumentModel.class;
099                break;
100            case "documents":
101                consume = DocumentModelList.class;
102                break;
103            case "blob":
104                consume = Blob.class;
105                break;
106            case "blobs":
107                consume = Blobs.class;
108                break;
109            default:
110                consume = Object.class;
111                break;
112            }
113        } else {
114            consume = p.length == 0 ? Void.TYPE : p[0];
115        }
116    }
117
118    public boolean isIterable() {
119        return false;
120    }
121
122    public int getPriority() {
123        return priority;
124    }
125
126    public OperationType getOperation() {
127        return op;
128    }
129
130    public final Class<?> getOutputType() {
131        return produce;
132    }
133
134    public final Class<?> getInputType() {
135        return consume;
136    }
137
138    /**
139     * Return 0 for no match.
140     */
141    public int inputMatch(Class<?> in) {
142        if (consume == in) {
143            return priority > 0 ? priority : EXACT_MATCH_PRIORITY;
144        }
145        if (consume.isAssignableFrom(in)) {
146            return priority > 0 ? priority : ISTANCE_OF_PRIORITY;
147        }
148        if (op.getService().isTypeAdaptable(in, consume)) {
149            return priority > 0 ? priority : ADAPTABLE_PRIORITY;
150        }
151        if (consume == Void.TYPE) {
152            return priority > 0 ? priority : VOID_PRIORITY;
153        }
154        return 0;
155    }
156
157    protected Object doInvoke(OperationContext ctx, Map<String, Object> args)
158            throws OperationException, ReflectiveOperationException {
159        Object target = op.newInstance(ctx, args);
160        Object input = ctx.getInput();
161        if (consume == Void.TYPE) {
162            // preserve last output for void methods
163            Object out = method.invoke(target);
164            return produce == Void.TYPE ? input : out;
165        }
166        if (input == null || !consume.isAssignableFrom(input.getClass())) {
167            // try to adapt
168            input = op.getService().getAdaptedValue(ctx, input, consume);
169        }
170        return method.invoke(target, input);
171    }
172
173    public Object invoke(OperationContext ctx, Map<String, Object> args) throws OperationException {
174        try {
175            return doInvoke(ctx, args);
176        } catch (InvocationTargetException e) {
177            Throwable t = e.getTargetException();
178            if (t instanceof OperationException) {
179                throw (OperationException) t;
180            } else if (t instanceof NuxeoException) {
181                NuxeoException nuxeoException = (NuxeoException) t;
182                nuxeoException.addInfo(getExceptionMessage());
183                throw nuxeoException;
184            } else {
185                throw new OperationException(getExceptionMessage(), t);
186            }
187        } catch (ReflectiveOperationException e) {
188            throw new OperationException(getExceptionMessage(), e);
189        }
190    }
191
192    protected String getExceptionMessage() {
193        String exceptionMessage = "Failed to invoke operation " + op.getId();
194        if (op.getAliases() != null && op.getAliases().length > 0) {
195            exceptionMessage += " with aliases " + Arrays.toString(op.getAliases());
196        }
197        return exceptionMessage;
198    }
199
200    @Override
201    public String toString() {
202        return getClass().getSimpleName() + "(" + method + ", " + priority + ")";
203    }
204
205    @Override
206    // used for methods of the same class, so ignore the class
207    public int compareTo(InvokableMethod o) {
208        // compare on name
209        int cmp = method.getName().compareTo(o.method.getName());
210        if (cmp != 0) {
211            return cmp;
212        }
213        // same name, compare on parameter types
214        Class<?>[] pt = method.getParameterTypes();
215        Class<?>[] opt = o.method.getParameterTypes();
216        // smaller length first
217        cmp = pt.length - opt.length;
218        if (cmp != 0) {
219            return cmp;
220        }
221        // compare parameter classes lexicographically
222        for (int i = 0; i < pt.length; i++) {
223            cmp = pt[i].getName().compareTo(opt[i].getName());
224            if (cmp != 0) {
225                return cmp;
226            }
227        }
228        return 0;
229    }
230
231    public Method getMethod() {
232        return method;
233    }
234
235    public Class<?> getProduce() {
236        return produce;
237    }
238
239    public Class<?> getConsume() {
240        return consume;
241    }
242}