DirectControlServlet.java 18 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
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.ArrayList;
import java.util.Set;
import java.util.Date;
import java.util.List;
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 java.util.Iterator;
import java.sql.Timestamp;

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 javax.servlet.http.Cookie;

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.base.util.UtilIO;
import org.ofbiz.base.util.UtilValidate;
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.DispatchContext;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ModelService;
import org.ofbiz.service.ServiceContainer;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;

import groovy.lang.GroovyClassLoader;
import groovy.lang.Script;

import org.codehaus.groovy.runtime.InvokerHelper;
import org.ofbiz.base.json.JSON;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

public class DirectControlServlet extends HttpServlet {
    public static final String module = DirectControlServlet.class.getName();
    public static final Map<String, String> serviceURLMappings = new HashMap<String, String>();
    private String sessionTokenName = "_AUTHTOKEN";
    private String checkSessionService;

    public void init(ServletConfig config) throws ServletException {
        // get the mapping file for this webapp
        ServletContext context = config.getServletContext();
        String mappingFile = context.getInitParameter("serviceURLMappings");
        Debug.logInfo("Mapping file: " + mappingFile, module);

        if (context.getInitParameter("sessionTokenName") != null) {
            sessionTokenName = context.getInitParameter("sessionTokenName");
        }

        if (mappingFile == null) {
            Debug.logInfo("No mapping file configured", module);
        } else {
            try {
                    BufferedReader in = new BufferedReader(new InputStreamReader(context.getResourceAsStream(mappingFile)));
                    String line;
                    while ((line = in.readLine()) != null) {
                        if (line.startsWith("#")) {
                            continue;
                        }
                        String[] confItem = line.split("=");
                        serviceURLMappings.put(confItem[0], confItem[1]);
                    }
            } catch (IOException ex) {
                Debug.logInfo("Could not read mapping file " + mappingFile, module);
                throw new ServletException("Could not read mapping file " + mappingFile);
            }
        }

        checkSessionService = context.getInitParameter("checkSessionService");
        Debug.logInfo("Checking session with service: " + checkSessionService, module);
    }

    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        String contentType = request.getContentType();
        try {
            Debug.logInfo("getPathInfo: " + pathInfo +
                    " request.getContentType: " + contentType, module);

            if (pathInfo == null || pathInfo.length() == 0) {
                return;
            }
            pathInfo = pathInfo.substring(1).replaceAll(":", ".");

            // Determine type of request and load the context from JSON content or
            // parameter values accordingly
            if (contentType != null) {
                int semi = contentType.indexOf(";");
                if (semi != -1) {
                    contentType = contentType.substring(0, semi);
                }
            }

            // Determine the request method for service lookup and parameter filters
            String method = "";
            method = request.getParameter("_method");
            String httpMethod = request.getMethod();
            if (method == null && httpMethod != null) method = httpMethod;
            if (method == null) method = "GET";

            // Load context
            Map<String, Object> context = new HashMap<String, Object>();

            // Directly copy request parameters into context.
            for (Enumeration<String> params = request.getParameterNames(); params.hasMoreElements();) {
                String param = params.nextElement();
                Object[] values = request.getParameterValues(param);
                if (!"sessionId".equals(param) && !"_method".equals(param)) {
                    context.put(param, values.length == 1 ? values[0] : values);
                }
            }

            if ("application/json".equals(contentType)) {
                // Read request body as JSON and insert into the context
                JSON json = new JSON(request.getReader());
                Map<String,Object> items = json.JSONObject();
                for (String key : items.keySet()) {
                    context.put(key, items.get(key));
                }
            } else if ("text/csv".equals(contentType)) {
                Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(request.getReader());
                List<List<String>> data = new ArrayList<List<String>>();
                for (CSVRecord record : records) {
                    List<String> row = new ArrayList<String>();
                    String cell = null;
                    Iterator<String> i=record.iterator(); 
                    while (i.hasNext()) {
                        row.add(i.next());
                    }
                    data.add(row);
                }
                context.put("data", data);
            } else {
                // Check if the request is a backbone style "emulateJSON" request
                if (contentType != null && contentType.indexOf("x-www-form-urlencoded") != -1 && request.getParameter("model") != null) {
                    Debug.logInfo("MODEL: " + request.getParameter("model"), module);
                    JSON json = new JSON(new StringReader(request.getParameter("model")));
                    Map<String,Object> items = json.JSONObject();
                    for (String key : items.keySet()) {
                        if (!"sessionId".equals(key)) {
                            context.put(key, items.get(key));
                        }
                    }
                }
            }

            Delegator delegator = getDelegator(request.getServletContext());
            LocalDispatcher dispatcher = getDispatcher(request.getServletContext());

            // If there is a mapping for this pathInfo, run the corresponding service
            // otherwise, return an error
            String serviceName = serviceURLMappings.get(pathInfo + "#" + method);
            Debug.logInfo("Service name " + serviceName, module);
            if (serviceName == null) {
                serviceName = serviceURLMappings.get(pathInfo);
                if (serviceName == null) {
                    response.setStatus(404);

                    Debug.logInfo("No mapping found for " + pathInfo + "#" + method, module);

                    PrintWriter writer = response.getWriter();
                    writer.println("No mapping found for URL \"" + pathInfo + "\"");
                    writer.flush();
                    writer.close();
                    return;
                }
            }

            // Check if there is an output handler
            String outputHandler = "JSON";
            if (serviceName.indexOf("|") != -1) {
                String[] parts = serviceName.split("\\|");
                serviceName = parts[0];
                outputHandler = parts[1];
            }

            Debug.logInfo("Service name" +serviceName + " mapped for " + pathInfo + "#" + method, module);

            // If the sessionId parameter is set, attempt to look up the corresponding
            // UserLogin and apply it to the service context
            String authToken = request.getParameter("sessionId");
            if (authToken != null) {
                GenericValue authTokenEntity = EntityUtil.getFirst(
                    EntityUtil.filterByDate(
                        delegator.findList("Visit", 
                            EntityCondition.makeCondition("cookie", 
                                EntityOperator.EQUALS, authToken),
                            null, null, null, false)
                    )
                );

                if (authTokenEntity != null) {
                    String userLoginId = authTokenEntity.getString("userLoginId");
                    if (UtilValidate.isNotEmpty(userLoginId)) {
                        GenericValue userLogin = EntityUtil.getFirst(
                                delegator.findList("UserLogin",
                                        EntityCondition.makeCondition("userLoginId", 
                                                EntityOperator.EQUALS, 
                                                userLoginId.toLowerCase()), 
                                                null, null, null, true));
                        if (userLogin != null) {
                            context.put("userLogin", userLogin);
                        }

                        // prolong the session
                        if (UtilValidate.isNotEmpty(checkSessionService)) {
                            dispatcher.runSync(checkSessionService, UtilMisc.<String, Object>toMap("authSessionId", authToken, "userLogin", userLogin));
                        }
                    }
                }
            }

            Debug.logInfo("USERLOGIN " + context.get("userLogin") + " AUTHTOKEN " + authToken, module);

            DispatchContext dctx = dispatcher.getDispatchContext();
            ModelService model = dctx.getModelService(serviceName);

            // some needed info for when running the service
            Locale locale = UtilHttp.getLocale(request);
            TimeZone timeZone = UtilHttp.getTimeZone(request);

            List<Object> errorMessages = new ArrayList<Object>();

            context = model.makeValid(context, ModelService.IN_PARAM, true, errorMessages, timeZone, locale);

            Map<String, Object> result = dispatcher.runSync(serviceName, context);

            result.remove("responseMessage");

            if (result.get("errorMessage") != null) {
                response.setStatus(400);
            }

            // Set to expire far in the past.
            response.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");

            // Set standard HTTP/1.1 no-cache headers.
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");

            // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");

            // Set standard HTTP/1.0 no-cache header.
            response.setHeader("Pragma", "no-cache");

            if ("JSON".equals(outputHandler)) {
                response.setContentType("application/x-json");

                PrintWriter writer = response.getWriter();

                JsonConfig jsonConfig = new JsonConfig();
                jsonConfig.registerJsonValueProcessor(Date.class, new ISODateValueProcessor());
                jsonConfig.registerJsonValueProcessor(Timestamp.class, new ISODateValueProcessor());
                JSONObject json = JSONObject.fromObject(result, jsonConfig);
                String jsonStr = json.toString();
                response.setContentLength(jsonStr.getBytes("UTF8").length);
                writer.write(jsonStr);
                writer.flush();
                writer.close();
            }

            if ("CSV".equals(outputHandler)) {
                response.setContentType("text/csv");

                // Find the first list
                List resList = null;
                for (Object o : result.values()) {
                    if (o instanceof List) {
                        resList = (List) o;
                        break;
                    } 
                }

                if (resList != null) {
                    PrintWriter writer = response.getWriter();
                    List<Map> data = null;
                    if (resList.get(1) instanceof List) {
                        data = (List<Map>)(resList.get(1));
                    } else {
                        data = resList;
                    }

                    if (data.size() > 0) {
                        Set keys = ((Map) data.get(0)).keySet();
                        Iterator hi = keys.iterator();
                        StringBuffer csvBuf = new StringBuffer();
                        while(hi.hasNext()) {
                            csvBuf.append(hi.next());
                            if (hi.hasNext()) csvBuf.append(",");
                        }
                        writer.println(csvBuf);

                        for (Map row : data) {
                            Iterator i = keys.iterator();
                            csvBuf = new StringBuffer();
                            while(i.hasNext()) {
                                Object val = row.get(i.next());
                                if (!"null".equals("" + val)) csvBuf.append(val);
                                if (i.hasNext()) csvBuf.append(",");
                            }
                            writer.println(csvBuf);
                        }
                    }

                    writer.flush();
                    writer.close();
                }
            }

            if ("PDF".equals(outputHandler)) {
                LibreOfficeRenderer.service(request, response, result);
            }
        } catch (Throwable t) {
            response.setStatus(500);
            PrintWriter writer = response.getWriter();
            Debug.logInfo("Exception processing request", module);
            Debug.logInfo(t, module);
            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.logInfo("[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.logInfo("No localDispatcherName specified in the web.xml file", module);
            dispatcherName = delegator.getDelegatorName();
        }

        LocalDispatcher dispatcher = ServiceContainer.getLocalDispatcher(dispatcherName, delegator);
        if (dispatcher == null) {
            Debug.logInfo("[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.logInfo("[ContextFilter.init] ERROR: delegator factory returned null for delegatorName \"" + delegatorName + "\"", module);
            }
        }
        return delegator;
    }

    protected static class ISODateValueProcessor implements JsonValueProcessor {
        public ISODateValueProcessor() {
        }

        public Object processArrayValue( Object value, JsonConfig jsonConfig ) {
            return value;
        }

        public Object processObjectValue( String key, Object value, JsonConfig jsonConfig ) {
            return process(value, jsonConfig);
        }

        private Object process( Object value, JsonConfig jsonConfig ) {
            String newValue = value.toString();
            return newValue;
        }
    }
}