view http/src/luan/modules/http/LuanHandler.java @ 743:2c41f2aec92f

improve Rpc and implement rpc call for local webserver
author Franklin Schmidt <fschmidt@gmail.com>
date Wed, 13 Jul 2016 17:27:35 -0600
parents ca169567ce07
children 3f461f85243d
line wrap: on
line source

package luan.modules.http;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import luan.LuanState;
import luan.LuanTable;
import luan.LuanFunction;
import luan.LuanException;
import luan.modules.PackageLuan;


public class LuanHandler extends AbstractHandler {
	private final LuanState luan;
	private final Logger logger;
	private String welcomeFile = "index.html";

	public LuanHandler(LuanState luan,String loggerRoot) {
		this.luan = luan;
		if( loggerRoot==null )
			loggerRoot = "";
		logger = LoggerFactory.getLogger(loggerRoot+LuanHandler.class.getName());
	}

	@Override public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response) 
		throws IOException
	{
		if( target.endsWith("/") )
			target += welcomeFile;
		try {
			if( !HttpServicer.service(luan,request,response,"site:"+target+".luan") )
				return;
		} catch(LuanException e) {
			String err = e.getFullMessage();
			logger.error(err);
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,err);
		}
		baseRequest.setHandled(true);
	}

	public void setWelcomeFile(String welcomeFile) {
		this.welcomeFile = welcomeFile;
	}

	@Override protected void doStop() throws Exception {
		synchronized(luan) {
			luan.close();
		}
//System.out.println("qqqqqqqqqqqqqqqqqqqq doStop "+this);
		super.doStop();
	}
/*
	@Override public void destroy() {
System.out.println("qqqqqqqqqqqqqqqqqqqq destroy "+this);
		super.destroy();
	}
*/

	public Object call_rpc(String fnName,Object... args) throws LuanException {
		return callRpc(luan,fnName,args);
	}

	public static Object callRpc(LuanState luan,String fnName,Object... args) throws LuanException {
		synchronized(luan) {
			LuanTable rpc = (LuanTable)PackageLuan.require(luan,"luan:Rpc.luan");
			LuanTable fns = (LuanTable)rpc.get(luan,"functions");
			LuanFunction fn = (LuanFunction)fns.get(luan,fnName);
			if( fn == null )
				throw new LuanException( "function not found: " + fnName );
			return fn.call(luan,args);
		}
	}

}