7df44925 by Ean Schuessler

New component for DirectControlServlet

0 parents
<?xml version="1.0"?>
<!--
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.
-->
<project name="direct-control" default="jar" basedir=".">
<first id="possible.ofbiz.home.common.xml">
<resources>
<fileset dir="..">
<include name="ofbiz/common.xml"/>
</fileset>
<fileset dir="/">
<include name="srv/ofbiz-upstream/common.xml"/>
<include name="opt/ofbiz-upstream/common.xml"/>
<include name="job/ofbiz-upstream/common.xml"/>
</fileset>
</resources>
</first>
<dirname property="possible.ofbiz.home.dir" file="${toString:possible.ofbiz.home.common.xml}"/>
<property name="ofbiz.home.dir" value="${possible.ofbiz.home.dir}"/>
<import file="${ofbiz.home.dir}/common.xml"/>
<!-- ================================================================== -->
<!-- Initialization of all property settings -->
<!-- ================================================================== -->
<property name="desc" value="direct-control"/>
<property name="name" value="direct-control"/>
<path id="local.class.path">
<!--<fileset dir="${lib.dir}" includes="*.jar"/>-->
<fileset dir="${ofbiz.home.dir}/framework/webapp/lib" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/framework/webapp/build/lib" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/framework/base/lib" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/framework/base/lib/commons" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/framework/base/lib/scripting" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/framework/base/lib/j2eespecs" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/framework/base/build/lib" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/framework/entity/lib" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/framework/entity/build/lib" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/framework/security/build/lib" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/framework/service/lib" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/framework/service/build/lib" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/framework/minilang/build/lib" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/framework/common/build/lib" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/framework/webapp/build/lib" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/applications/party/build/lib" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/applications/product/build/lib" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/applications/marketing/build/lib" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/applications/order/build/lib" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/applications/accounting/build/lib" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/applications/securityext/build/lib" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/framework/start/build/lib" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/framework/catalina/lib" includes="*.jar"/>
</path>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<ofbiz-component name="direct-api"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://www.ofbiz.org/dtds/ofbiz-component.xsd">
<resource-loader name="main" type="component"/>
<classpath type="dir" location="config"/>
<classpath type="jar" location="lib/*"/>
<classpath type="jar" location="build/lib/*"/>
</ofbiz-component>
package com.brainfood.ofbiz;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.Collections;
import java.util.Collection;
import java.util.Map;
import java.net.URL;
import java.net.MalformedURLException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Enumeration;
import java.util.Locale;
import java.util.TimeZone;
import javolution.util.FastList;
import javax.script.ScriptContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GroovyUtil;
import org.ofbiz.base.util.ScriptHelper;
import org.ofbiz.base.util.ScriptUtil;
import org.ofbiz.base.util.StringUtil;
import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.DelegatorFactory;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityUtil;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ServiceContainer;
import groovy.lang.GroovyClassLoader;
import groovy.lang.Script;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.ofbiz.base.json.JSON;
import org.ofbiz.base.json.ParseException;
import net.sf.json.JSONObject;
public class DirectControlServlet extends HttpServlet {
public static final String module = DirectControlServlet.class.getName();
public static final Map<String, String> serviceURLMappings = new HashMap<String, String>();
public void init(ServletConfig config) throws ServletException {
// get the mapping file for this webapp
ServletContext context = config.getServletContext();
String mappingFile = context.getInitParameter("serviceURLMappings");
Debug.logError("Mapping file: " + mappingFile, module);
if (mappingFile == null) {
Debug.logError("No mapping file configured", module);
} else {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(context.getResourceAsStream(mappingFile)));
String line;
while ((line = in.readLine()) != null) {
String[] confItem = line.split("=");
serviceURLMappings.put(confItem[0], confItem[1]);
}
} catch (IOException ex) {
Debug.logError("Could not read mapping file " + mappingFile, module);
throw new ServletException("Could not read mapping file " + mappingFile);
}
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String method = "";
Debug.logInfo("request.getPathInfo: " + request.getPathInfo(), module);
Debug.logInfo("request.getContentType: " + request.getContentType(), module);
String pathInfo = request.getPathInfo();
if (pathInfo == null || pathInfo.length() == 0) {
return;
}
pathInfo = pathInfo.substring(1).replaceAll(":", ".");
try {
Delegator delegator = getDelegator(request.getServletContext());
LocalDispatcher dispatcher = getDispatcher(request.getServletContext());
// Build context
Map<String, Object> context = new HashMap<String, Object>();
String authToken = null;
// Handle if this is a form post
String contentType = request.getContentType();
if (contentType != null && contentType.indexOf("application/x-www-form-urlencoded") != -1) {
method = request.getParameter("_method");
// If this is a backbone PUT/DELETE emulated call then handle it
Debug.logInfo("Method: " + method, module);
if ("PUT".equals(method) || "DELETE".equals(method) || "CALL".equals(method)) {
if (!"CALL".equals(method)) context.put("_method", method);
JSON json = new JSON(new StringReader(request.getParameter("model")));
Map<String,Object> items = json.JSONObject();
authToken = (String) items.get("_AUTHTOKEN");
for (String key : items.keySet()) {
if (!"_AUTHTOKEN".equals(key)) {
context.put(key, items.get(key));
Debug.logInfo("parameter '" + key + "'=" + items.get(key), module);
}
}
} else {
authToken = request.getParameter("_AUTHTOKEN");
for (Enumeration<String> params = request.getParameterNames(); params.hasMoreElements();) {
String param = params.nextElement();
Object[] values = request.getParameterValues(param);
if (!"_AUTHTOKEN".equals(param)) {
context.put(param, values.length == 1 ? values[0] : values);
Debug.logInfo("parameter '" + param + "'=" + context.get(param), module);
}
}
}
} else {
Debug.logError("Unsupported form encoding", module);
}
// If there is a mapping for this pathInfo, run the corresponding service
// otherwise, return an error
String serviceName = serviceURLMappings.get(pathInfo) + "#" + method;
if (serviceName == null) {
serviceName = serviceURLMappings.get(pathInfo);
if (serviceName == null) {
response.setStatus(400);
PrintWriter writer = response.getWriter();
writer.println("No mapping found for URL \"" + pathInfo + "\"");
writer.flush();
writer.close();
return;
}
}
// If the _AUTHTOKEN parameter is set, attempt to look up the corresponding
// UserLogin and apply it to the service context
if (authToken != null) {
GenericValue authTokenEntity = EntityUtil.getFirst(
delegator.findList("Visit",
EntityCondition.makeCondition("cookie",
EntityOperator.EQUALS, authToken),
null, null, null, true));
if (authTokenEntity != null &&
authTokenEntity.get("userLoginId") != null) {
GenericValue userLogin = EntityUtil.getFirst(
delegator.findList("UserLogin",
EntityCondition.makeCondition("userLoginId",
EntityOperator.EQUALS,
authTokenEntity.get("userLoginId")),
null, null, null, true));
if (userLogin != null) {
context.put("userLogin", userLogin);
}
}
}
// some needed info for when running the service
Locale locale = UtilHttp.getLocale(request);
TimeZone timeZone = UtilHttp.getTimeZone(request);
Map<String, Object> result = dispatcher.runSync(serviceName, context);
System.err.println("RESULT:" + result);
result.remove("responseMessage");
if (result.get("errorMessage") != null) {
response.setStatus(400);
}
response.setContentType("application/x-json");
PrintWriter writer = response.getWriter();
JSONObject json = JSONObject.fromObject(result);
String jsonStr = json.toString();
response.setContentLength(jsonStr.getBytes("UTF8").length);
writer.write(jsonStr);
Debug.logWarning("JSON result [%s]", module, jsonStr);
writer.flush();
writer.close();
} catch (Throwable t) {
response.setStatus(400);
PrintWriter writer = response.getWriter();
while (t != null) {
t.printStackTrace(writer);
t = t.getCause();
}
writer.flush();
writer.close();
}
}
protected static LocalDispatcher getDispatcher(ServletContext servletContext) {
LocalDispatcher dispatcher = (LocalDispatcher) servletContext.getAttribute("dispatcher");
if (dispatcher == null) {
Delegator delegator = getDelegator(servletContext);
dispatcher = makeWebappDispatcher(servletContext, delegator);
servletContext.setAttribute("dispatcher", dispatcher);
}
return dispatcher;
}
/** This method only sets up a dispatcher for the current webapp and passed in delegator, it does not save it to the ServletContext or anywhere else, just returns it */
public static LocalDispatcher makeWebappDispatcher(ServletContext servletContext, Delegator delegator) {
if (delegator == null) {
Debug.logError("[ContextFilter.init] ERROR: delegator not defined.", module);
return null;
}
// get the unique name of this dispatcher
String dispatcherName = servletContext.getInitParameter("localDispatcherName");
if (dispatcherName == null) {
Debug.logError("No localDispatcherName specified in the web.xml file", module);
dispatcherName = delegator.getDelegatorName();
}
LocalDispatcher dispatcher = ServiceContainer.getLocalDispatcher(dispatcherName, delegator);
if (dispatcher == null) {
Debug.logError("[ContextFilter.init] ERROR: dispatcher could not be initialized.", module);
}
return dispatcher;
}
protected static Delegator getDelegator(ServletContext servletContext) {
Delegator delegator = (Delegator) servletContext.getAttribute("delegator");
if (delegator == null) {
String delegatorName = servletContext.getInitParameter("entityDelegatorName");
if (delegatorName == null || delegatorName.length() <= 0) {
delegatorName = "default";
}
if (Debug.verboseOn()) Debug.logVerbose("Setup Entity Engine Delegator with name " + delegatorName, module);
delegator = DelegatorFactory.getDelegator(delegatorName);
servletContext.setAttribute("delegator", delegator);
if (delegator == null) {
Debug.logError("[ContextFilter.init] ERROR: delegator factory returned null for delegatorName \"" + delegatorName + "\"", module);
}
}
return delegator;
}
}