Author: adrianc
Date: Mon Mar 12 23:20:55 2012 New Revision: 1299924 URL: http://svn.apache.org/viewvc?rev=1299924&view=rev Log: More JSR-223 work - added a ScriptHelper object to the bindings. Also added a demonstration to the JavaScript test service. Added: ofbiz/trunk/framework/base/src/org/ofbiz/base/util/ScriptHelper.java (with props) ofbiz/trunk/framework/base/src/org/ofbiz/base/util/ScriptHelperFactory.java (with props) ofbiz/trunk/framework/common/src/META-INF/services/org.ofbiz.base.util.ScriptHelperFactory ofbiz/trunk/framework/common/src/org/ofbiz/common/scripting/ ofbiz/trunk/framework/common/src/org/ofbiz/common/scripting/ContextHelper.java (with props) ofbiz/trunk/framework/common/src/org/ofbiz/common/scripting/ScriptHelperFactoryImpl.java (with props) ofbiz/trunk/framework/common/src/org/ofbiz/common/scripting/ScriptHelperImpl.java (with props) Modified: ofbiz/trunk/framework/base/src/META-INF/services/javax.script.ScriptEngineFactory ofbiz/trunk/framework/base/src/org/ofbiz/base/util/ScriptUtil.java ofbiz/trunk/framework/common/script/org/ofbiz/common/JavaScriptTest.js ofbiz/trunk/framework/common/servicedef/services_test.xml Modified: ofbiz/trunk/framework/base/src/META-INF/services/javax.script.ScriptEngineFactory URL: http://svn.apache.org/viewvc/ofbiz/trunk/framework/base/src/META-INF/services/javax.script.ScriptEngineFactory?rev=1299924&r1=1299923&r2=1299924&view=diff ============================================================================== --- ofbiz/trunk/framework/base/src/META-INF/services/javax.script.ScriptEngineFactory (original) +++ ofbiz/trunk/framework/base/src/META-INF/services/javax.script.ScriptEngineFactory Mon Mar 12 23:20:55 2012 @@ -1 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + bsh.engine.BshScriptEngineFactory Added: ofbiz/trunk/framework/base/src/org/ofbiz/base/util/ScriptHelper.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/framework/base/src/org/ofbiz/base/util/ScriptHelper.java?rev=1299924&view=auto ============================================================================== --- ofbiz/trunk/framework/base/src/org/ofbiz/base/util/ScriptHelper.java (added) +++ ofbiz/trunk/framework/base/src/org/ofbiz/base/util/ScriptHelper.java Mon Mar 12 23:20:55 2012 @@ -0,0 +1,166 @@ +/******************************************************************************* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + *******************************************************************************/ +package org.ofbiz.base.util; + +import java.util.List; +import java.util.Map; + +import javax.script.ScriptException; + +/** + * A script helper object. The OFBiz scripting framework will include an instance of this class in the script's bindings. + * <p>The scripting language will determine how the helper is used. Most languages will access it as a variable:<br /> + * <code>partyValue = ofbiz.findOne("Party");</code><br /> + * while other languages might access it as a native method or function:<br /> + * <code>partyValue = findOne("Party");</code></p> + */ +public interface ScriptHelper { + + /** + * Extracts service IN parameters from <code>inputMap</code> and returns them in a new <code>Map</code>. + * + * @param serviceName + * @param inputMap + * @return The matching service parameters + * @throws ScriptException + */ + Map<String, ? extends Object> createServiceMap(String serviceName, Map<String, ? extends Object> inputMap) throws ScriptException; + + /** + * Sets the event/service status to error status. + * + * @param message + */ + void error(String message); + + /** + * Evaluates a <code>String</code> and returns the result. + * + * @param original + * @return + */ + String evalString(String original); + + /** + * Sets the event/service status to failure status. + * + * @param message + */ + void failure(String message); + + /** + * Returns a <code>List</code> of <code>GenericValue</code>s. + * @param entityName + * @param fields + * @return + * @throws ScriptException + */ + List<Map<String, Object>> findList(String entityName, Map<String, ? extends Object> fields) throws ScriptException; + + /** + * Finds a <code>GenericValue</code> by primary key. The helper will construct a primary key from existing variables. + * @param entityName + * @return + * @throws ScriptException + */ + Map<String, Object> findOne(String entityName) throws ScriptException; + + /** + * Finds a <code>GenericValue</code> by primary key. The helper will construct a primary key from existing variables + * and/or <code>fields</code>. + * @param entityName + * @param fields + * @param args + * @return + * @throws ScriptException + */ + Map<String, Object> findOne(String entityName, Map<String, ? extends Object> fields, Map<String, ? extends Object> args) throws ScriptException; + + /** + * Logs an error message. + * + * @param message + */ + void logError(String message); + + /** + * Logs an info message. + * + * @param message + */ + void logInfo(String message); + + /** + * Logs a warning message. + * + * @param message + */ + void logWarning(String message); + + /** + * Creates a new, empty <code>GenericValue</code>. + * @param entityName + * @return + * @throws ScriptException + */ + Map<String, Object> makeValue(String entityName) throws ScriptException; + + /** + * Creates a new, empty <code>GenericValue</code>. + * + * @param entityName + * @param fields + * @return + * @throws ScriptException + */ + Map<String, Object> makeValue(String entityName, Map<String, Object> fields) throws ScriptException; + + /** + * Runs a service synchronously. + * + * @param serviceName + * @param inputMap + * @return + * @throws ScriptException + */ + Map<String, ? extends Object> runService(String serviceName, Map<String, ? extends Object> inputMap) throws ScriptException; + + /** + * Runs a service synchronously. + * + * @param serviceName + * @param inputMap + * @param args + * @return + * @throws ScriptException + */ + Map<String, ? extends Object> runService(String serviceName, Map<String, ? extends Object> inputMap, Map<String, ? extends Object> args) throws ScriptException; + + /** + * Sets the event/service status to success status. + */ + void success(); + + /** + * Sets the event/service status to success status. + * + * @param message + */ + void success(String message); +} Propchange: ofbiz/trunk/framework/base/src/org/ofbiz/base/util/ScriptHelper.java ------------------------------------------------------------------------------ svn:eol-style = native Propchange: ofbiz/trunk/framework/base/src/org/ofbiz/base/util/ScriptHelper.java ------------------------------------------------------------------------------ svn:keywords = Author Date Id Rev URL Added: ofbiz/trunk/framework/base/src/org/ofbiz/base/util/ScriptHelperFactory.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/framework/base/src/org/ofbiz/base/util/ScriptHelperFactory.java?rev=1299924&view=auto ============================================================================== --- ofbiz/trunk/framework/base/src/org/ofbiz/base/util/ScriptHelperFactory.java (added) +++ ofbiz/trunk/framework/base/src/org/ofbiz/base/util/ScriptHelperFactory.java Mon Mar 12 23:20:55 2012 @@ -0,0 +1,31 @@ +/******************************************************************************* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + *******************************************************************************/ +package org.ofbiz.base.util; + +import javax.script.ScriptContext; + +import org.ofbiz.base.lang.Factory; + +/** + * A <code>ScriptHelper</code> factory. + */ +public interface ScriptHelperFactory extends Factory<ScriptHelper, ScriptContext> { + + ScriptHelper getInstance(ScriptContext context); +} Propchange: ofbiz/trunk/framework/base/src/org/ofbiz/base/util/ScriptHelperFactory.java ------------------------------------------------------------------------------ svn:eol-style = native Propchange: ofbiz/trunk/framework/base/src/org/ofbiz/base/util/ScriptHelperFactory.java ------------------------------------------------------------------------------ svn:keywords = Author Date Id Rev URL Modified: ofbiz/trunk/framework/base/src/org/ofbiz/base/util/ScriptUtil.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/framework/base/src/org/ofbiz/base/util/ScriptUtil.java?rev=1299924&r1=1299923&r2=1299924&view=diff ============================================================================== --- ofbiz/trunk/framework/base/src/org/ofbiz/base/util/ScriptUtil.java (original) +++ ofbiz/trunk/framework/base/src/org/ofbiz/base/util/ScriptUtil.java Mon Mar 12 23:20:55 2012 @@ -25,8 +25,10 @@ import java.net.MalformedURLException; import java.net.URL; import java.util.Collection; import java.util.Collections; +import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.ServiceLoader; import java.util.Set; import javax.script.Bindings; @@ -62,8 +64,11 @@ public final class ScriptUtil { public static final String PARAMETERS_KEY = "parameters"; /** The result map bindings key. */ public static final String RESULT_KEY = "result"; + /** The <code>ScriptHelper</code> key. */ + public static final String SCRIPT_HELPER_KEY = "ofbiz"; private static final UtilCache<String, CompiledScript> parsedScripts = UtilCache.createUtilCache("script.ParsedScripts", 0, 0, false); private static final Object[] EMPTY_ARGS = {}; + private static ScriptHelperFactory helperFactory = null; static { if (Debug.infoOn()) { @@ -94,6 +99,15 @@ public final class ScriptUtil { } } } + Iterator<ScriptHelperFactory> iter = ServiceLoader.load(ScriptHelperFactory.class).iterator(); + if (iter.hasNext()) { + helperFactory = iter.next(); + if (Debug.verboseOn()) { + Debug.logVerbose("ScriptHelper factory set to " + helperFactory.getClass().getName(), module); + } + } else { + Debug.logWarning("ScriptHelper factory not found", module); + } } /** @@ -186,6 +200,10 @@ public final class ScriptUtil { context.put(WIDGET_CONTEXT_KEY, context); context.put("context", context); ScriptContext scriptContext = new SimpleScriptContext(); + ScriptHelper helper = createScriptHelper(scriptContext); + if (helper != null) { + context.put(SCRIPT_HELPER_KEY, helper); + } Bindings bindings = new SimpleBindings(context); scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE); return scriptContext; @@ -206,12 +224,23 @@ public final class ScriptUtil { context.put(WIDGET_CONTEXT_KEY, context); context.put("context", context); ScriptContext scriptContext = new SimpleScriptContext(); + ScriptHelper helper = createScriptHelper(scriptContext); + if (helper != null) { + context.put(SCRIPT_HELPER_KEY, helper); + } Bindings bindings = new ProtectedBindings(context, Collections.unmodifiableSet(protectedKeys)); scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE); return scriptContext; } - /** + public static ScriptHelper createScriptHelper(ScriptContext context) { + if (helperFactory != null) { + return helperFactory.getInstance(context); + } + return null; + } + + /** * Executes a script <code>String</code> and returns the result. * * @param language Modified: ofbiz/trunk/framework/common/script/org/ofbiz/common/JavaScriptTest.js URL: http://svn.apache.org/viewvc/ofbiz/trunk/framework/common/script/org/ofbiz/common/JavaScriptTest.js?rev=1299924&r1=1299923&r2=1299924&view=diff ============================================================================== --- ofbiz/trunk/framework/common/script/org/ofbiz/common/JavaScriptTest.js (original) +++ ofbiz/trunk/framework/common/script/org/ofbiz/common/JavaScriptTest.js Mon Mar 12 23:20:55 2012 @@ -25,6 +25,17 @@ if (message) { var result = "[no message received]"; } +if (ofbiz) { + var partyValue = ofbiz.findOne("PartyNameView"); + if (partyValue) { + var foundMessage = ofbiz.evalString(" Found Party ${partyValue.groupName}${partyValue.firstName} ${partyValue.lastName}"); + successMessage = successMessage + foundMessage; + ofbiz.logInfo(successMessage); + } else { + ofbiz.logInfo("Party not found with partyId ${parameters.partyId}"); + } +} + function testFunction(context) { if (message) { var successMessage = "Got message [" + message + "] and finished fine"; Modified: ofbiz/trunk/framework/common/servicedef/services_test.xml URL: http://svn.apache.org/viewvc/ofbiz/trunk/framework/common/servicedef/services_test.xml?rev=1299924&r1=1299923&r2=1299924&view=diff ============================================================================== --- ofbiz/trunk/framework/common/servicedef/services_test.xml (original) +++ ofbiz/trunk/framework/common/servicedef/services_test.xml Mon Mar 12 23:20:55 2012 @@ -199,6 +199,7 @@ under the License. <service name="testScriptEngineJavaScript" engine="script" location="component://common/script/org/ofbiz/common/JavaScriptTest.js" invoke=""> <description>Test Script Engine With JavaScript</description> <attribute name="message" type="String" mode="IN" optional="true"/> + <attribute name="partyId" type="String" mode="IN" optional="true"/> <attribute name="result" type="String" mode="OUT"/> </service> Added: ofbiz/trunk/framework/common/src/META-INF/services/org.ofbiz.base.util.ScriptHelperFactory URL: http://svn.apache.org/viewvc/ofbiz/trunk/framework/common/src/META-INF/services/org.ofbiz.base.util.ScriptHelperFactory?rev=1299924&view=auto ============================================================================== --- ofbiz/trunk/framework/common/src/META-INF/services/org.ofbiz.base.util.ScriptHelperFactory (added) +++ ofbiz/trunk/framework/common/src/META-INF/services/org.ofbiz.base.util.ScriptHelperFactory Mon Mar 12 23:20:55 2012 @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +org.ofbiz.common.scripting.ScriptHelperFactoryImpl Added: ofbiz/trunk/framework/common/src/org/ofbiz/common/scripting/ContextHelper.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/framework/common/src/org/ofbiz/common/scripting/ContextHelper.java?rev=1299924&view=auto ============================================================================== --- ofbiz/trunk/framework/common/src/org/ofbiz/common/scripting/ContextHelper.java (added) +++ ofbiz/trunk/framework/common/src/org/ofbiz/common/scripting/ContextHelper.java Mon Mar 12 23:20:55 2012 @@ -0,0 +1,268 @@ +/******************************************************************************* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + *******************************************************************************/ +package org.ofbiz.common.scripting; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Locale; +import java.util.Map; +import java.util.TimeZone; + +import javax.script.ScriptContext; +import javax.script.ScriptEngine; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.ofbiz.base.util.Assert; +import org.ofbiz.base.util.ScriptUtil; +import org.ofbiz.base.util.collections.FlexibleMapAccessor; +import org.ofbiz.base.util.string.FlexibleStringExpander; +import org.ofbiz.entity.Delegator; +import org.ofbiz.entity.GenericValue; +import org.ofbiz.security.Security; +import org.ofbiz.security.authz.Authorization; +import org.ofbiz.service.LocalDispatcher; + +/** + * A set of <code>ScriptContext</code> convenience methods for scripting engines. + */ +public final class ContextHelper { + + public static final String module = ContextHelper.class.getName(); + private static final int EVENT = 1; + private static final int SERVICE = 2; + private static final int UNKNOWN = 3; + + private final ScriptContext context; + private final int scriptType; + + public ContextHelper(ScriptContext context) { + Assert.notNull("context", context); + this.context = context; + if (context.getAttribute("request") != null) { + this.scriptType = EVENT; + } else if (context.getAttribute("dctx") != null) { + this.scriptType = SERVICE; + } else { + this.scriptType = UNKNOWN; + } + } + + public Object addBinding(String key, Object value) { + return getBindings().put(key, value); + } + + /** Expands environment variables delimited with ${} */ + public String expandString(String original) { + return FlexibleStringExpander.expandString(original, getBindings()); + } + + public Authorization getAuthz() { + return (Authorization) this.context.getAttribute("authz"); + } + + public Map<String, Object> getBindings() { + return this.context.getBindings(ScriptContext.ENGINE_SCOPE); + } + + public Delegator getDelegator() { + return (Delegator) this.context.getAttribute("delegator"); + } + + public LocalDispatcher getDispatcher() { + return (LocalDispatcher) this.context.getAttribute("dispatcher"); + } + + public <T> T getEnv(FlexibleMapAccessor<T> fma) { + return fma.get(getBindings()); + } + + /** + * Gets the named value from the environment. Supports the "." (dot) syntax to access + * Map members and the "[]" (bracket) syntax to access List entries. This value is + * expanded, supporting the insertion of other environment values using the "${}" + * notation. + * + * @param key + * The name of the environment value to get. Can contain "." and "[]" + * syntax elements as described above. + * @return The environment value if found, otherwise null. + */ + public <T> T getEnv(String key) { + String ekey = this.expandString(key); + FlexibleMapAccessor<T> fma = FlexibleMapAccessor.getInstance(ekey); + return getEnv(fma); + } + + public Iterator<Map.Entry<String, Object>> getEnvEntryIterator() { + return getBindings().entrySet().iterator(); + } + + public Locale getLocale() { + return (Locale) this.context.getAttribute("locale"); + } + + @SuppressWarnings("unchecked") + public Object getParameter(String key) { + Map<?, ?> parameters = (Map) this.context.getAttribute(ScriptUtil.PARAMETERS_KEY); + return parameters != null ? parameters.get(key) : null; + } + + @SuppressWarnings("unchecked") + public Map<String, Object> getParameters() { + return (Map<String, Object>) this.context.getAttribute(ScriptUtil.PARAMETERS_KEY); + } + + public HttpServletRequest getRequest() { + return (HttpServletRequest) this.context.getAttribute("request"); + } + + public HttpServletResponse getResponse() { + return (HttpServletResponse) this.context.getAttribute("response"); + } + + @SuppressWarnings("unchecked") + public Object getResult(String key) { + Map<?, ?> results = (Map) this.context.getAttribute(ScriptUtil.RESULT_KEY); + return results != null ? results.get(key) : null; + } + + @SuppressWarnings("unchecked") + public Map<String, Object> getResults() { + return (Map<String, Object>) this.context.getAttribute(ScriptUtil.RESULT_KEY); + } + + public String getScriptName() { + String scriptName = (String) this.context.getAttribute(ScriptEngine.FILENAME); + return scriptName != null ? scriptName : "Unknown"; + } + + public Security getSecurity() { + return (Security) this.context.getAttribute("security"); + } + + public TimeZone getTimeZone() { + return (TimeZone) this.context.getAttribute("timeZone"); + } + + public GenericValue getUserLogin() { + return (GenericValue) this.context.getAttribute("userLogin"); + } + + public boolean isEvent() { + return this.scriptType == EVENT; + } + + public boolean isService() { + return this.scriptType == SERVICE; + } + + /** + * Calls putEnv for each entry in the Map, thus allowing for the additional + * flexibility in naming supported in that method. + */ + public void putAllEnv(Map<String, ? extends Object> values) { + for (Map.Entry<String, ? extends Object> entry : values.entrySet()) { + this.putEnv(entry.getKey(), entry.getValue()); + } + } + + public <T> void putEnv(FlexibleMapAccessor<T> fma, T value) { + fma.put(getBindings(), value); + } + + /** + * Puts the named value in the environment. Supports the "." (dot) syntax to access + * Map members and the "[]" (bracket) syntax to access List entries. If the brackets + * for a list are empty the value will be appended to end of the list, otherwise the + * value will be set in the position of the number in the brackets. If a "+" (plus + * sign) is included inside the square brackets before the index number the value will + * inserted/added at that index instead of set at that index. This value is expanded, + * supporting the insertion of other environment values using the "${}" notation. + * + * @param key + * The name of the environment value to get. Can contain "." syntax + * elements as described above. + * @param value + * The value to set in the named environment location. + */ + public <T> void putEnv(String key, T value) { + String ekey = this.expandString(key); + FlexibleMapAccessor<T> fma = FlexibleMapAccessor.getInstance(ekey); + this.putEnv(fma, value); + } + + @SuppressWarnings("unchecked") + public void putParameter(String key, Object value) { + Map<String, Object> parameters = (Map) this.context.getAttribute(ScriptUtil.PARAMETERS_KEY); + if (parameters == null) { + parameters = new HashMap<String, Object>(); + this.context.setAttribute(ScriptUtil.PARAMETERS_KEY, parameters, ScriptContext.ENGINE_SCOPE); + } + parameters.put(key, value); + } + + @SuppressWarnings("unchecked") + public void putResult(String key, Object value) { + Map<String, Object> results = (Map) this.context.getAttribute(ScriptUtil.RESULT_KEY); + if (results == null) { + results = new HashMap<String, Object>(); + this.context.setAttribute(ScriptUtil.RESULT_KEY, results, ScriptContext.ENGINE_SCOPE); + } + results.put(key, value); + } + + @SuppressWarnings("unchecked") + public void putResults(Map<String, Object> results) { + Map<String, Object> existingResults = (Map) this.context.getAttribute(ScriptUtil.RESULT_KEY); + if (existingResults == null) { + existingResults = new HashMap<String, Object>(); + this.context.setAttribute(ScriptUtil.RESULT_KEY, results, ScriptContext.ENGINE_SCOPE); + } + existingResults.putAll(results); + } + + public Object removeBinding(String key) { + return getBindings().remove(key); + } + + public <T> T removeEnv(FlexibleMapAccessor<T> fma) { + return fma.remove(getBindings()); + } + + /** + * Removes the named value from the environment. Supports the "." (dot) syntax to + * access Map members and the "[]" (bracket) syntax to access List entries. This value + * is expanded, supporting the insertion of other environment values using the "${}" + * notation. + * + * @param key + * The name of the environment value to get. Can contain "." syntax + * elements as described above. + */ + public <T> T removeEnv(String key) { + String ekey = this.expandString(key); + FlexibleMapAccessor<T> fma = FlexibleMapAccessor.getInstance(ekey); + return removeEnv(fma); + } + + public void setUserLogin(GenericValue userLogin, String userLoginEnvName) { + putEnv(userLoginEnvName, userLogin); + } +} Propchange: ofbiz/trunk/framework/common/src/org/ofbiz/common/scripting/ContextHelper.java ------------------------------------------------------------------------------ svn:eol-style = native Propchange: ofbiz/trunk/framework/common/src/org/ofbiz/common/scripting/ContextHelper.java ------------------------------------------------------------------------------ svn:keywords = Author Date Id Rev URL Added: ofbiz/trunk/framework/common/src/org/ofbiz/common/scripting/ScriptHelperFactoryImpl.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/framework/common/src/org/ofbiz/common/scripting/ScriptHelperFactoryImpl.java?rev=1299924&view=auto ============================================================================== --- ofbiz/trunk/framework/common/src/org/ofbiz/common/scripting/ScriptHelperFactoryImpl.java (added) +++ ofbiz/trunk/framework/common/src/org/ofbiz/common/scripting/ScriptHelperFactoryImpl.java Mon Mar 12 23:20:55 2012 @@ -0,0 +1,35 @@ +/******************************************************************************* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + *******************************************************************************/ +package org.ofbiz.common.scripting; + +import javax.script.ScriptContext; + +import org.ofbiz.base.util.ScriptHelper; +import org.ofbiz.base.util.ScriptHelperFactory; + +/** + * An implementation of the <code>ScriptHelperFactory</code> interface. + */ +public final class ScriptHelperFactoryImpl implements ScriptHelperFactory { + + @Override + public ScriptHelper getInstance(ScriptContext context) { + return new ScriptHelperImpl(context); + } +} Propchange: ofbiz/trunk/framework/common/src/org/ofbiz/common/scripting/ScriptHelperFactoryImpl.java ------------------------------------------------------------------------------ svn:eol-style = native Propchange: ofbiz/trunk/framework/common/src/org/ofbiz/common/scripting/ScriptHelperFactoryImpl.java ------------------------------------------------------------------------------ svn:keywords = Author Date Id Rev URL Added: ofbiz/trunk/framework/common/src/org/ofbiz/common/scripting/ScriptHelperImpl.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/framework/common/src/org/ofbiz/common/scripting/ScriptHelperImpl.java?rev=1299924&view=auto ============================================================================== --- ofbiz/trunk/framework/common/src/org/ofbiz/common/scripting/ScriptHelperImpl.java (added) +++ ofbiz/trunk/framework/common/src/org/ofbiz/common/scripting/ScriptHelperImpl.java Mon Mar 12 23:20:55 2012 @@ -0,0 +1,283 @@ +/******************************************************************************* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + *******************************************************************************/ +package org.ofbiz.common.scripting; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.script.ScriptContext; +import javax.script.ScriptException; + +import org.ofbiz.base.util.Assert; +import org.ofbiz.base.util.Debug; +import org.ofbiz.base.util.ScriptHelper; +import org.ofbiz.base.util.UtilGenerics; +import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.entity.Delegator; +import org.ofbiz.entity.GenericEntityException; +import org.ofbiz.entity.GenericPK; +import org.ofbiz.entity.GenericValue; +import org.ofbiz.entity.model.ModelEntity; +import org.ofbiz.service.GenericServiceException; +import org.ofbiz.service.ModelService; +import org.ofbiz.service.ServiceUtil; + +/** + * An implementation of the <code>ScriptHelper</code> interface. + */ +public final class ScriptHelperImpl implements ScriptHelper { + + public static final String module = ScriptHelperImpl.class.getName(); + private static final Map<String, ? extends Object> EMPTY_ARGS = Collections.unmodifiableMap(new HashMap<String, Object>()); + + private static GenericValue runFindByPrimaryKey(ModelEntity modelEntity, ContextHelper ctxHelper, boolean useCache, boolean autoFieldMap, + Map<String, ? extends Object> fieldMap, List<String> selectFieldList) throws ScriptException { + Map<String, Object> entityContext = new HashMap<String, Object>(); + Delegator delegator = ctxHelper.getDelegator(); + Map<String, Object> context = ctxHelper.getBindings(); + if (autoFieldMap) { + GenericValue tempVal = delegator.makeValue(modelEntity.getEntityName()); + Object parametersObj = context.get("parameters"); + if (parametersObj != null && parametersObj instanceof Map<?, ?>) { + tempVal.setAllFields(UtilGenerics.checkMap(parametersObj), true, null, Boolean.TRUE); + } + tempVal.setAllFields(context, true, null, Boolean.TRUE); + entityContext.putAll(tempVal); + } + if (fieldMap != null) { + entityContext.putAll(fieldMap); + } + entityContext.put("locale", context.get("locale")); + entityContext.put("timeZone", context.get("timeZone")); + modelEntity.convertFieldMapInPlace(entityContext, delegator); + entityContext.remove("locale"); + entityContext.remove("timeZone"); + Set<String> fieldsToSelect = null; + if (selectFieldList != null) { + fieldsToSelect = new HashSet<String>(selectFieldList); + } + if (fieldsToSelect != null && useCache) { + String errMsg = "Error running script " + ctxHelper.getScriptName() + ": Problem invoking the findOne method: Cannot specify selectFieldList argument when useCache is set to true "; + Debug.logWarning(errMsg, module); + throw new ScriptException(errMsg); + } + GenericValue valueOut = null; + GenericPK entityPK = delegator.makePK(modelEntity.getEntityName(), entityContext); + if (entityPK.containsPrimaryKey(true)) { + try { + if (useCache) { + valueOut = delegator.findOne(entityPK.getEntityName(), entityPK, true); + } else { + if (fieldsToSelect != null) { + valueOut = delegator.findByPrimaryKeyPartial(entityPK, fieldsToSelect); + } else { + valueOut = delegator.findOne(entityPK.getEntityName(), entityPK, false); + } + } + } catch (GenericEntityException e) { + String errMsg = "Error running script " + ctxHelper.getScriptName() + ": Problem invoking the findOne method: " + e.getMessage(); + Debug.logWarning(e, errMsg, module); + throw new ScriptException(errMsg); + } + } else { + if (Debug.warningOn()) { + Debug.logWarning("Error running script " + ctxHelper.getScriptName() + ": Returning null because found incomplete primary key in find: " + entityPK, module); + } + } + return valueOut; + } + + private final ContextHelper ctxHelper; + + public ScriptHelperImpl(ScriptContext context) { + this.ctxHelper = new ContextHelper(context); + } + + public Map<String, ? extends Object> createServiceMap(String serviceName, Map<String, ? extends Object> inputMap) throws ScriptException { + Assert.notNull("serviceName", serviceName, "inputMap", inputMap); + Map<String, Object> toMap = new HashMap<String, Object>(); + ModelService modelService = null; + try { + modelService = ctxHelper.getDispatcher().getDispatchContext().getModelService(serviceName); + } catch (GenericServiceException e) { + String errMsg = "Error running script " + ctxHelper.getScriptName() + ": Problem invoking the createServiceMap method: get service definition for service name [" + serviceName + "]: " + e.getMessage(); + Debug.logWarning(e, errMsg, module); + throw new ScriptException(errMsg); + } + toMap.putAll(modelService.makeValid(inputMap, "IN", true, null, ctxHelper.getTimeZone(), ctxHelper.getLocale())); + return toMap; + } + + @Override + public void error(String message) { + if (ctxHelper.isEvent()) { + ctxHelper.putResult("_error_message_", ctxHelper.expandString(message)); + ctxHelper.putResult("_response_code_", "error"); + } else if (ctxHelper.isService()) { + ctxHelper.putResults(ServiceUtil.returnError(ctxHelper.expandString(message))); + } + } + + @Override + public String evalString(String original) { + return ctxHelper.expandString(original); + } + + @Override + public void failure(String message) { + if (ctxHelper.isEvent()) { + ctxHelper.putResult("_error_message_", ctxHelper.expandString(message)); + ctxHelper.putResult("_response_code_", "fail"); + } else if (ctxHelper.isService()) { + ctxHelper.putResults(ServiceUtil.returnFailure(ctxHelper.expandString(message))); + } + } + + public List<Map<String, Object>> findList(String entityName, Map<String, ? extends Object> fields) throws ScriptException { + try { + return UtilGenerics.checkList(ctxHelper.getDelegator().findByAnd(entityName, fields)); + } catch (GenericEntityException e) { + String errMsg = "Error running script " + ctxHelper.getScriptName() + ": Problem invoking the findList method: " + e.getMessage(); + Debug.logWarning(e, errMsg, module); + throw new ScriptException(errMsg); + } + } + + public Map<String, Object> findOne(String entityName) throws ScriptException { + return findOne(entityName, null, EMPTY_ARGS); + } + + public Map<String, Object> findOne(String entityName, Map<String, ? extends Object> fields, Map<String, ? extends Object> args) throws ScriptException { + Assert.notNull("entityName", entityName); + if (args == null) { + args = EMPTY_ARGS; + } + boolean useCache = "true".equals(args.get("useCache")); + boolean autoFieldMap = !"false".equals(args.get("autoFieldMap")); + List<String> selectFieldList = UtilGenerics.checkList(args.get("selectFieldList")); + ModelEntity modelEntity = ctxHelper.getDelegator().getModelEntity(entityName); + if (modelEntity == null) { + throw new ScriptException("Error running script " + ctxHelper.getScriptName() + " - no entity definition found for entity name [" + entityName + "]"); + } + return runFindByPrimaryKey(modelEntity, ctxHelper, useCache, autoFieldMap, fields, selectFieldList); + } + + public void logError(String message) { + String expandedMessage = ctxHelper.expandString(message); + Debug.logError("[".concat(ctxHelper.getScriptName()).concat("] ").concat(expandedMessage), module); + } + + public void logInfo(String message) { + String expandedMessage = ctxHelper.expandString(message); + Debug.logInfo("[".concat(ctxHelper.getScriptName()).concat("] ").concat(expandedMessage), module); + } + + public void logWarning(String message) { + String expandedMessage = ctxHelper.expandString(message); + Debug.logWarning("[".concat(ctxHelper.getScriptName()).concat("] ").concat(expandedMessage), module); + } + + public Map<String, Object> makeValue(String entityName) throws ScriptException { + return ctxHelper.getDelegator().makeValidValue(entityName); + } + + public Map<String, Object> makeValue(String entityName, Map<String, Object> fields) throws ScriptException { + return ctxHelper.getDelegator().makeValidValue(entityName, fields); + } + + public Map<String, ? extends Object> runService(String serviceName, Map<String, ? extends Object> inputMap) throws ScriptException { + return runService(serviceName, inputMap, EMPTY_ARGS); + } + + public Map<String, ? extends Object> runService(String serviceName, Map<String, ? extends Object> inputMap, Map<String, ? extends Object> args) throws ScriptException { + Assert.notNull("serviceName", serviceName, "args", args); + boolean includeUserLogin = !"false".equals(args.get("includeUserLoginStr")); + String requireNewTransactionStr = (String) args.get("requireNewTransaction"); + int transactionTimeout = -1; + if (UtilValidate.isNotEmpty(requireNewTransactionStr)) { + String timeoutStr = (String) args.get("transactionTimout"); + if (!UtilValidate.isEmpty(timeoutStr)) { + try { + transactionTimeout = Integer.parseInt(timeoutStr); + } catch (NumberFormatException e) { + Debug.logWarning(e, "Setting timeout to 0 (default)", module); + transactionTimeout = 0; + } + } + } + Map<String, Object> inMap = new HashMap<String, Object>(inputMap); + if (includeUserLogin && !inMap.containsKey("userLogin")) { + GenericValue userLogin = ctxHelper.getUserLogin(); + if (userLogin != null) { + inMap.put("userLogin", userLogin); + } + } + if (!inMap.containsKey("locale") && ctxHelper.getLocale() != null) { + inMap.put("locale", ctxHelper.getLocale()); + } + if (!inMap.containsKey("timeZone") && ctxHelper.getTimeZone() != null) { + inMap.put("timeZone", ctxHelper.getTimeZone()); + } + Map<String, Object> result = null; + try { + if (UtilValidate.isEmpty(requireNewTransactionStr) && transactionTimeout < 0) { + result = ctxHelper.getDispatcher().runSync(serviceName, inMap); + } else { + ModelService modelService = ctxHelper.getDispatcher().getDispatchContext().getModelService(serviceName); + boolean requireNewTransaction = modelService.requireNewTransaction; + int timeout = modelService.transactionTimeout; + if (UtilValidate.isNotEmpty(requireNewTransactionStr)) { + requireNewTransaction = "true".equals(requireNewTransactionStr); + } + if (transactionTimeout >= 0) { + timeout = transactionTimeout; + } + result = ctxHelper.getDispatcher().runSync(serviceName, inMap, timeout, requireNewTransaction); + } + } catch (GenericServiceException e) { + String errMsg = "Error running script " + ctxHelper.getScriptName() + " [problem invoking the [" + serviceName + "] service: " + e.getMessage(); + Debug.logWarning(e, errMsg, module); + throw new ScriptException(errMsg); + } + return result; + } + + @Override + public void success() { + if (ctxHelper.isEvent()) { + ctxHelper.putResult("_response_code_", "success"); + } else if (ctxHelper.isService()) { + ctxHelper.putResults(ServiceUtil.returnSuccess()); + } + } + + @Override + public void success(String message) { + if (ctxHelper.isEvent()) { + ctxHelper.putResult("_event_message_", ctxHelper.expandString(message)); + ctxHelper.putResult("_response_code_", "success"); + } else if (ctxHelper.isService()) { + ctxHelper.putResults(ServiceUtil.returnSuccess(ctxHelper.expandString(message))); + } + } +} Propchange: ofbiz/trunk/framework/common/src/org/ofbiz/common/scripting/ScriptHelperImpl.java ------------------------------------------------------------------------------ svn:eol-style = native Propchange: ofbiz/trunk/framework/common/src/org/ofbiz/common/scripting/ScriptHelperImpl.java ------------------------------------------------------------------------------ svn:keywords = Author Date Id Rev URL |
Free forum by Nabble | Edit this page |