DirectControlServlet.java 25.4 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 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
package com.brainfood.ofbiz;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStream;
import java.util.Collections;
import java.util.Collection;
import java.util.Map;
import java.net.URL;
import java.net.MalformedURLException;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
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.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ReadListener;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
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 javax.servlet.http.Part;

import org.ofbiz.base.lang.JSON;
import org.ofbiz.base.util.Base64;
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.UtilGenerics;
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 org.apache.commons.fileupload.MultipartStream;
import org.apache.commons.fileupload.ParameterParser;
import org.apache.http.HeaderElement;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicHeaderValueParser;

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

import org.codehaus.groovy.runtime.InvokerHelper;

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;
    private ServletConfig config;

    public void init(ServletConfig config) throws ServletException {
        // get the mapping file for this webapp
        this.config = config;
        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 the request method for service lookup and parameter filters
            String method = request.getParameter("_method");
            String httpMethod = request.getMethod();
            if (method == null) {
                method = request.getMethod();
            }
            if (method == null) {
                method = "GET";
            }

            // 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(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;
                }
            }
            Debug.logInfo("Service name %s" +serviceName + " mapped for " + pathInfo + "#" + method, module, serviceName, pathInfo);

            AsyncContext context = request.startAsync();
            AsyncHandler asyncHandler = new AsyncHandler(serviceName, request, response, context);
            context.addListener(asyncHandler);
            asyncHandler.sin.setReadListener(asyncHandler);
        } 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 interface Cleanup {
        void cleanup();
    }

    protected class AsyncHandler implements ReadListener, WriteListener, AsyncListener {
        protected final String serviceName;
        protected final String outputHandler;

        protected final File directory;
        protected final HttpServletRequest request;
        protected final HttpServletResponse response;

        protected final ServletInputStream sin;
        protected final AsyncContext context;

        protected final File tmpFile;
        protected final OutputStream tmpOut;

        protected final List<Cleanup> cleanups = new ArrayList<Cleanup>();

        protected AsyncHandler(String serviceName, HttpServletRequest request, HttpServletResponse response, AsyncContext context) throws IOException, NoSuchAlgorithmException {
            this.directory = (File) request.getServletContext().getAttribute("javax.servlet.context.tempdir");
            this.request = request;
            this.response = response;

            this.sin = request.getInputStream();
            this.context = context;

            this.tmpFile = deleteFileWhenDone(File.createTempFile("dcs", ".body", directory));
            this.tmpOut = new BufferedOutputStream(new FileOutputStream(tmpFile));

            String outputHandler = "JSON";
            if (serviceName.indexOf("|") != -1) {
                String[] parts = serviceName.split("\\|");
                serviceName = parts[0];
                outputHandler = parts[1];
            }
            this.serviceName = serviceName;
            this.outputHandler = outputHandler;
        }


        public void onAllDataRead() throws IOException {
            //System.err.println("onAllDataRead");
            sin.close();

            tmpOut.flush();
            tmpOut.close();

            try {
                processRequest();
            } catch (IOException e) {
                throw e;
            } catch (Exception e) {
                e.printStackTrace();
                throw (IOException) new IOException(e.getMessage()).initCause(e);
            } finally {
                context.complete();
            }
        }

        protected File deleteFileWhenDone(final File file) {
            file.deleteOnExit();
            cleanups.add(new Cleanup() {
                public void cleanup() {
                    file.delete();
                }
            });
            return file;
        }

        protected void processRequest() throws Exception {
            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);
                context.put(param, values.length == 1 ? values[0] : values);
            }
            context.remove("_method");

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

            if ("application/json".equals(contentType)) {
                // Read request body as JSON and insert into the context
                Map<String, Object> items = UtilGenerics.cast(JSON.from(UtilIO.readString(new FileReader(tmpFile))).toObject(Map.class));
                for (Object key : items.keySet()) {
                    context.put((String) key, items.get(key));
                }
            } else if ("text/csv".equals(contentType)) {
                Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(new FileReader(tmpFile));
                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 if (rawContentType != null && rawContentType.indexOf("multipart/form-data") != -1) {
                //System.err.println("contentType[" + rawContentType + "]");
                String boundary = rawContentType.substring("multipart/form-data; boundary=".length());
                MessageDigest digest = MessageDigest.getInstance("SHA-256");
                MultipartStream multipartStream = new MultipartStream(new FileInputStream(tmpFile), boundary.getBytes(), 65536, null);
                ParameterParser parameterParser = new ParameterParser();

                boolean hasNext = multipartStream.skipPreamble();
                while (hasNext) {
                    String[] headerLines = multipartStream.readHeaders().split("[\r\n]+(?! )");
                    Map<String, String> headerData = new HashMap<String, String>();
                    for (String headerLine: headerLines) {
                        //System.err.println("headerLine[" + headerLine + "]");
                        String[] headerNameAndRawValue = headerLine.split(": ", 2);
                        headerData.put(headerNameAndRawValue[0].toLowerCase(), headerNameAndRawValue[1]);
                        HeaderElement[] headerElements = BasicHeaderValueParser.INSTANCE.parseElements(headerNameAndRawValue[1], null);
                        for (HeaderElement headerElement: headerElements) {
                            String headerName = headerElement.getName();
                            String prefix = (headerNameAndRawValue[0] + "." + headerName).toLowerCase();
                            headerData.put(prefix, headerElement.getValue());
                            for (NameValuePair nameValuePair: headerElement.getParameters()) {
                                headerData.put(prefix + "." + nameValuePair.getName(), nameValuePair.getValue());
                            }
                        }
                    }
                    //System.err.println("header=" + JSON.from(headerData).toString());
                    String fieldName = headerData.get("content-disposition.form-data.name");
                    String fileName = headerData.get("content-disposition.form-data.filename");
                    if (fileName == null) {
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        multipartStream.readBodyData(baos);
                        context.put(fieldName, baos.toString());
                    } else {
                        File tmpFilePart = deleteFileWhenDone(File.createTempFile("dcs", ".part", directory));
                        digest.reset();
                        DigestOutputStream digestOut = new DigestOutputStream(new FileOutputStream(tmpFilePart), digest);
                        multipartStream.readBodyData(digestOut);
                        context.put(fieldName, tmpFilePart);
                        String sha256 = new String(Base64.base64Encode(digest.digest()));
                        context.put(fieldName + ".contentType", headerData.get("content-type"));
                        context.put(fieldName + ".sha256", sha256);
                    }
                    hasNext = multipartStream.readBoundary();
                }
            } 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);
                    Map<String, Object> items = UtilGenerics.cast(JSON.from(UtilIO.readString(new FileReader(tmpFile))).toObject(Map.class));
                    for (Object key : items.keySet()) {
                        if (!"sessionId".equals(key)) {
                            context.put((String) key, items.get(key));
                        }
                    }
                }
            }

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

            // Check if there is an output handler

            // 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();

                String jsonStr = JSON.from(result).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<Map> resList = null;
                for (Object o : result.values()) {
                    if (o instanceof List) {
                        resList = (List<Map>) 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);
            }

            //sout.setWriteListener(this);
        }


        public void onDataAvailable() throws IOException {
            byte[] buffer = new byte[65536];
            int numRead;
            while (sin.isReady() && (numRead = sin.read(buffer)) > 0) {
                tmpOut.write(buffer, 0, numRead);
            }
        }

        public void onWritePossible() throws IOException {
            context.complete();
        }

        public void onError(Throwable t) {
            t.printStackTrace();
            context.complete();
        }

        public void onComplete(AsyncEvent event) throws IOException {
            //System.err.println("onComplete");
            for (Cleanup cleanup: cleanups) {
                cleanup.cleanup();
            }
        }

        public void onError(AsyncEvent event) {
            event.getThrowable().printStackTrace();
        }

        public void onStartAsync(AsyncEvent event) {
            //System.err.println("onStartAsync");
        }

        public void onTimeout(AsyncEvent event) {
            ////System.err.println("onTimeout");
        }
    }

    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;
        }
    }
}