001/*
002 *
003 * Copyright (c) 2015 The Regents of the University of California.
004 * All rights reserved.
005 *
006 * '$Author: crawl $'
007 * '$Date: 2017-08-23 22:42:39 -0700 (Wed, 23 Aug 2017) $' 
008 * '$Revision: 1375 $'
009 * 
010 * Permission is hereby granted, without written agreement and without
011 * license or royalty fees, to use, copy, modify, and distribute this
012 * software and its documentation for any purpose, provided that the above
013 * copyright notice and the following two paragraphs appear in all copies
014 * of this software.
015 *
016 * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
017 * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
018 * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
019 * THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
020 * SUCH DAMAGE.
021 *
022 * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
023 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
024 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
025 * PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
026 * CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
027 * ENHANCEMENTS, OR MODIFICATIONS.
028 *
029 */
030package org.kepler.webview.server.handler;
031
032import java.io.BufferedReader;
033import java.io.File;
034import java.io.StringReader;
035import java.net.HttpURLConnection;
036
037import org.apache.commons.io.FileUtils;
038import org.kepler.webview.actor.WebViewable;
039import org.kepler.webview.server.WebViewId;
040import org.kepler.webview.server.WebViewServer;
041
042import io.vertx.core.http.HttpServerRequest;
043import io.vertx.core.http.HttpServerResponse;
044import io.vertx.ext.web.RoutingContext;
045import ptolemy.kernel.util.NamedObj;
046import ptolemy.util.MessageHandler;
047
048public class ActorHandler extends BaseHandler {
049        
050    public ActorHandler(WebViewServer server) {
051        super(server);
052    }
053
054    @Override
055    public void handle(RoutingContext context) {
056
057        final long timestamp = System.currentTimeMillis();
058        
059        HttpServerRequest req = context.request();
060        HttpServerResponse response = context.response();
061        response.headers().set("Content-Type", "text/html");
062        response.setChunked(true);
063        
064        String actorEndPath = WebViewServer.findFile(_ACTOR_END_HTML);
065        if(actorEndPath == null) {
066            response.write("<html>\n<body>\n<h2>actor-end.html " +
067                   " not found.</h2>\n</body>\n</html>")
068              .setStatusCode(HttpURLConnection.HTTP_NOT_FOUND).end();
069            System.err.println("Unhandled http request (actor-end.html not found) for: " +
070              context.normalisedPath());
071            _server.log(req, context.user(), HttpURLConnection.HTTP_NOT_FOUND, timestamp);
072            return;
073        }
074
075        String actorId = req.params().get("param0");        
076        //System.out.println("wf name is: " + name +
077            //" actor name is " + actorName);
078        NamedObj namedObj = WebViewId.getNamedObj(actorId);
079        if (namedObj == null) {
080            response.write("<html>\n<body>\n<h2>Id " +
081                    actorId + " not found.</h2>\n</body>\n</html>")
082              .setStatusCode(HttpURLConnection.HTTP_NOT_FOUND).end();
083            _server.log(req, context.user(), HttpURLConnection.HTTP_NOT_FOUND, timestamp);
084            System.err.println("Unhandled http request (id not found) for: " +
085                context.normalisedPath());
086            return;
087        }       
088        
089        String name = namedObj.getFullName();
090        
091        //System.out.println("name = " + name);
092        if(!(namedObj instanceof WebViewable)) {
093            response.write("<html>\n<body>\n<h2>NamedObj " +
094                    name + " is not a WebViewable.</h2>\n</body>\n</html>")
095              .setStatusCode(HttpURLConnection.HTTP_NOT_FOUND).end();
096            _server.log(req, context.user(), HttpURLConnection.HTTP_NOT_FOUND, timestamp);
097            System.err.println("Unhandled http request (namedobj is not a webviewable) for: " +
098                context.normalisedPath());
099            return;
100        }
101        
102        WebViewable webView = (WebViewable) namedObj;
103                
104        String htmlStr;
105        try {
106            htmlStr = webView.getHTML();
107            if(htmlStr == null) {
108                MessageHandler.error("Could not read HTML for " + webView.getFullName());
109            } else {
110                StringBuilder buf = new StringBuilder();
111                try(StringReader stringReader = new StringReader(htmlStr);
112                        BufferedReader reader = new BufferedReader(stringReader);) {
113                    String line = reader.readLine();
114                    while(line != null) {
115                        if(line.trim().equals("</body>")) {
116                            String end = FileUtils.readFileToString(new File(actorEndPath));
117                            end = end.replaceAll("PATH", "\"" + actorId + "\"");
118                            buf.append(end);
119                        }
120                        buf.append(line).append('\n');
121                        line = reader.readLine();
122                    }
123                }                          
124                response.write(buf.toString());
125            }
126        } catch (Exception e) {
127            MessageHandler.error("Error reading HTML in WebView actor.", e);
128        }
129        response.setStatusCode(HttpURLConnection.HTTP_OK).end();
130        _server.log(req, context.user(), HttpURLConnection.HTTP_OK, timestamp);
131    }
132    
133    private final static String _ACTOR_END_HTML = "web-view" +
134            File.separator + "actor-end.html";
135}