001/* 002 * (C) Copyright 2006-2011 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.operations; 020 021import java.io.IOException; 022 023import org.nuxeo.ecm.automation.OperationContext; 024import org.nuxeo.ecm.automation.OperationException; 025import org.nuxeo.ecm.automation.core.Constants; 026import org.nuxeo.ecm.automation.core.annotations.Context; 027import org.nuxeo.ecm.automation.core.annotations.Operation; 028import org.nuxeo.ecm.automation.core.annotations.OperationMethod; 029import org.nuxeo.ecm.automation.core.annotations.Param; 030import org.nuxeo.ecm.automation.core.scripting.Scripting.GroovyScript; 031import org.nuxeo.ecm.automation.core.scripting.Scripting.MvelScript; 032import org.nuxeo.ecm.core.api.Blob; 033import org.nuxeo.ecm.core.api.Blobs; 034 035/** 036 * Run a script given as the input of the operation (as a blob). Note that this operation is available only as 037 * administrator 038 * 039 * @author <a href="mailto:[email protected]">Bogdan Stefanescu</a> 040 */ 041@Operation(id = RunInputScript.ID, category = Constants.CAT_SCRIPTING, label = "Run Input Script", description = "Run a script from the input blob. A blob comtaining script result is returned.", aliases = { "Context.RunInputScript" }) 042public class RunInputScript { 043 044 public static final String ID = "RunInputScript"; 045 046 @Context 047 protected OperationContext ctx; 048 049 @Param(name = "type", required = false, values = { "mvel", "groovy" }, widget = Constants.W_OPTION) 050 protected String type = "mvel"; 051 052 @OperationMethod 053 public Blob run(Blob blob) throws OperationException, IOException { 054 if (!ctx.getPrincipal().isAdministrator()) { 055 throw new OperationException("Not allowed. You must be administrator to run scripts"); 056 } 057 Object r = null; 058 if (type.equals("mvel")) { 059 r = MvelScript.compile(blob.getString()).eval(ctx); 060 } else if (type.equals("groovy")) { 061 r = new GroovyScript(blob.getString()).eval(ctx); 062 } else { 063 throw new OperationException("Unknown scripting language " + type); 064 } 065 if (r != null) { 066 Blob b = Blobs.createBlob(r.toString()); 067 b.setFilename("result"); 068 return b; 069 } 070 return null; 071 } 072 073}