处理请求

@param req ServletRequest
@param res ServletResponse
@return 是否处理成功
487540
public final boolean handle(HttpServletRequest req, HttpServletResponse res) {
		return handle(req, res, Request.getPath(req));
	}
253349
function (req, res) {

            //To avoid errors, escape table
            req.params.table = escape(req.params.table);

            //Get all fields from table
            lastQry = connection.query('SHOW COLUMNS FROM ??', req.params.table, function (err, rows) {
                if (err) return sendError(res, err.code);


                var fields, limit, order, where;


                //All general Settings


                //Select only certain columns?
                if (typeof req.query[settings.paramPrefix + "fields"] !== "undefined" && typeof req.query[settings.paramPrefix + "fields"] == "string" && req.query[settings.paramPrefix + "fields"] !== "") {
                    var req_fields = escape(req.query[settings.paramPrefix + "fields"]);
                    if (checkIfFieldsExist(req_fields, rows)) {
                        fields = req_fields;
                    } else {
                        return sendError(res, "Failed to fetch all fields specified in _fields");
                    }
                } else {
                    fields = '*';
                }

                //Parse order by and order direction
                if (typeof req.query[settings.paramPrefix + "order"] !== "undefined" && typeof req.query[settings.paramPrefix + "order"] === "object") {
                    var orderObj = req.query[settings.paramPrefix + "order"];
                    var orderArr = [];
                    for (var order_field in orderObj) {
                        if (orderObj.hasOwnProperty(order_field)) {
                            if (checkIfFieldsExist(order_field, rows)) {
                                if (orderObj[order_field].toUpperCase() == "ASC" || orderObj[order_field].toUpperCase() == "DESC") {
                                    orderArr.push(req.params.table + ".`" + order_field + "` " + orderObj[order_field].toUpperCase());
                                } else {
                                    return sendError(res, "Order option for " + order_field + " in _order is invalid. Please use either ASC or DESC");
                                }
                            } else {
                                return sendError(res, "Failed to fetch " + order_field + " specified in _order");
                            }
                        }
                    }
                    order = orderArr.join(',');
                }

                //Parse limit
                if (typeof req.query[settings.paramPrefix + "limit"] !== "undefined" && typeof req.query[settings.paramPrefix + "limit"] === "string" && req.query[settings.paramPrefix + "limit"] !== "") {

                    var limitStr = req.query[settings.paramPrefix + "limit"];


                    var limitArr = limitStr.split(',');
                    if (limitArr.length > 2) {
                        return sendError(res, "Limit specificed in _limit is invalid. Limit does not allow more than 2 comma separated values");
                    }
                    for (var i = 0; i < limitArr.length; i++) {
                        var lim = parseInt(limitArr[i]);
                        if (isNaN(lim)) {
                            return sendError(res, "Limit specificed in _limit is invalid. Please use a comma to separate start and amount");
                        }
                        limitArr[i] = lim;
                    }

                    limit = limitArr.join(',');

                }


                //Parse all other get params as selector
                var whereArr = [];

                for (var q in req.query) {
                    if (req.query.hasOwnProperty(q)) {
                        if (q.substr(0, 1) !== settings.paramPrefix) {
                            if (checkIfFieldsExist(q, rows)) {

                                if (typeof req.query[q] === "string") {
                                    //If it is a simple string, the api assumes = as the operator
                                    whereArr.push(mysql.format('?? = ?', [q, escape(req.query[q])]));

                                } else if (typeof req.query[q] === "object") {

                                    for (var selector in req.query[q]) {
                                        if (req.query[q].hasOwnProperty(selector)) {
                                            var op, val = connection.escape(escape(req.query[q][selector]));
                                            //MYSQLify the operator
                                            switch (selector.toUpperCase()) {
                                                case 'GREAT':
                                                    op = "> ";
                                                    break;
                                                case 'SMALL':
                                                    op = "< ";
                                                    break;
                                                case 'EQGREAT':
                                                    op = '>= ';
                                                    break;
                                                case 'EQSMALL':
                                                    op = '<= ';
                                                    break;
                                                case 'IN':
                                                    op = 'IN (';
                                                    val = escape(req.query[q][selector]).split(',').map(function (item) {
                                                        return connection.escape(item);
                                                    }).join(',') + ')';
                                                    break;
                                                case 'LIKE':
                                                    op = 'LIKE ';                                            
                                                    break;
                                                case 'EQ':
                                                    op = '= ';
                                                    break;
                                                default:
                                                    op = '= ';
                                                    break;
                                            }
                                            whereArr.push(mysql.format('?? ' + op + val, [q]));
                                        }
                                    }

                                } else {
                                    return sendError(res, "Can't read parameter specified for the field " + q + " in the table " + req.params.table);
                                }


                            } else {
                                return sendError(res, "Can't find the field" + q + " in the table " + req.params.table);
                            }
                        }
                    }
                }

                if (whereArr.length > 0) {
                    where = whereArr.join(' AND ')
                }

                //Bring in MYSQL syntax
                fields = fields ? fields : '*';
                order = order ? 'ORDER BY ' + order : '';
                limit = limit ? 'LIMIT ' + limit : '';
                where = where ? 'WHERE ' + where : '';

                //Fire query
                lastQry = connection.query("SELECT " + fields + " FROM ?? " + where + " " + order + " " + limit, [req.params.table], function (err, rows) {
                    if (err) return sendError(res, err.code);
                    res.send({
                        result: 'success',
                        json: rows,
                        table: req.params.table,
                        length: rows.length
                    });
                });
            });
        }
556351
public void save(HttpServletRequest req, HttpServletResponse res) {
		AuthenticationResult authResult = new AuthenticationResult(AuthResult.SUCCESS, (String) null);
		save(req, res, authResult);
		List<Cookie> cookieList = authResult.getCookies();
		if (cookieList != null && cookieList.size() > 0) {
			CookieHelper.addCookiesToResponse(cookieList, res);
		}
	}
958833
function jsonRet(req,res) {
    var state = 200;
    var data = {
        code:state,
        message:""
    };

    //错误判断（404）
    if(!req.input) {
        state = 404;
        req.app.yolog.log('error','error 404');
    } else if(req.input.error) {
        state = 500;
        data.message = req.input.message ? req.input.message:'';
        req.app.yolog.log('error','error 500',req.input);
    } else {
        data.data = res.proxyData;
    } 
    req.app.yolog.log('verbose','pjax vo: %j',data,{});
    data.code = state;
    res.status(state).json(data);
}
581890
function(res) {
    res.setEncoding('utf8');
    var data = "";
    res.on('data', function(chunk) {
      data+=chunk;
    });

    res.on('end', function() {
      // Get HTTP Statuscode and act according to situation
      var code = res.statusCode;
      try { // try to parse JSON
        var answer = JSON.parse(data);
      } catch (e) {
        var err = {};
        err.http_code = 500;
        err.message = "No valid JSON received: "+data;
        callback(err, null);
        return;
      }
      if(code >= 200 && code <= 206) { // request was successful
        callback(null, answer);
      } else if (code >= 300 && code <= 307) { // server send redirect
        // we do not follow anything the server wants us to follow right now, since this should never be the case.
        // instead let's raise an error.
        var err = new Object();
        err.http_code = 500;
        err.message = "Redirects not supported by pastyclient-node"
        callback(err, null);
      } else if (code >= 400 && code <= 418) { // client error
        if(typeof(answer.error) == "object") {
          var err = answer.error;
        } else if(answer.code != undefined && answer.message != undefined) { // New RestError, temporary support both 
          var err = answer;
          err.http_code = code;
        } else {
          var err = new Object();
          err.http_code = code;
          err.message = "Resource not found";
        }
        callback(err, null);
      } else if (code >= 500 && code <= 505) { // server error
        if(typeof(answer.error) == "object") {
          var err = answer.error;
        } else {
          var err = new Object();
          err.http_code = code;
          err.message = "Internal Server Error";
        }
        callback(err, null);
      } else {
        // Not existant HTTP code. Raise error.
        var err = new Object();
        err.http_code = 500;
        err.message = "HTTP Status Code "+code+" is not supported by pastyclient-node"
        callback(err, null);
      }
    });
  }
1049231
function(data, req, res, servConfig){
        if(!data.cnt) return false;
        // utils.log(utils.chalk.green("----------ajax json:\n", data.type));
        try{
            switch(data.type){
                case 'mjson': //处理mockjson
                    //utils.log(utils.chalk.green(mockjs.mock(JSON.parse(data.cnt))))
                    this.acao && res.setHeader("Access-Control-Allow-Origin","*");
                    data.cnt = JSON.stringify(mockjs.mock(JSON.parse(data.cnt)), null, 4);
                case 'json':
                    this.acao && res.setHeader("Access-Control-Allow-Origin","*");
                    res.writeHead(200, {
                        'Content-Type': utils.MIME['json']
                    });
                    res.write(data.cnt);
                    res.end();
                    break;
                case 'js':
                    //data = new vm.script(data[0]);
                    // 将分解好的url给mock用户*.js 
                    // 只能拦截所起服务下的mock 跨域的不能拦截需用fiddler或charles之类的代理到servermock所起服务下
                    req.parseUrl = req.wwwurl = url.parse(servConfig.protocol + '://' + req.headers.host + req.url);
                    var qstr = req.wwwurl.query ? qs.parse(req.wwwurl.query) : {},
                        query = {};
                    for(var i in qstr){
                        var $ = /(.+)\[(.+)\]/.exec(i);
                        // utils.log(utils.chalk.green("$: ", $));
                        $ ? (query[$[1]] || (query[$[1]] = {})) && (query[$[1]][$[2]] = qstr[i]):
                            query[i] = qstr[i];  
                    }
                    // utils.log(utils.chalk.green("qstr: ", qstr));
                    //extname === 'html' && utils.log(utils.chalk.green(req, '\n\n\n\n', req.wwwurl))
                    req.queryObj = req.wwwurl.queryObj = query;
                    //utils.log(utils.chalk.green('----------mock js func:\n', data.cnt.toString()));
                    vm.runInThisContext('(' + data.cnt + ')')(req, res, require);
                    break;
                default:
                    utils.log(utils.chalk.yellow("mock 暂只支持.mjson .json .js文件"));
                    res.end("mock 暂只支持.mjson .json .js文件");
            }
        } catch(e){
            utils.log(utils.chalk.red("mock error: "), e);
        }
        return true;
    }
1124770
function reqres(res, req) {
    if (req && req._headers) {
        throw new Error('Received response object where request object was expected');
    }
    this.res = res;
    this.req = req;
    if (res) {
        if (res.$ && res.$.data) {
            this.data = res.$.data;
        }
        else {
            this.data = { error: null };
            if (!res.$) {
                res.$ = this;
            }
        }
    }
}
313062
protected void doAction(final HttpServletRequest req, final HttpServletResponse resp, String action) {
        // Read the request.
        ApiRequest srequest;
        try {
            srequest = readRequest(req);
            srequest.setType(action);
        } catch (Exception e) {
            writeError(null, resp, e);
            return;
        }

        final CountDownLatch latch = new CountDownLatch(1);
        final ApiRequest finalRequest = srequest;

        // Now execute the request via the apiman engine
        IApiRequestExecutor executor = getEngine().executor(srequest, new IAsyncResultHandler<IEngineResult>() {
            @Override
            public void handle(IAsyncResult<IEngineResult> asyncResult) {
                if (asyncResult.isSuccess()) {
                    IEngineResult engineResult = asyncResult.getResult();
                    if (engineResult.isResponse()) {
                        try {
                            writeResponse(resp, engineResult.getApiResponse());
                            final ServletOutputStream outputStream = resp.getOutputStream();
                            engineResult.bodyHandler(new IAsyncHandler<IApimanBuffer>() {
                                @Override
                                public void handle(IApimanBuffer chunk) {
                                    try {
                                        if (chunk instanceof ByteBuffer) {
                                            byte [] buffer = (byte []) chunk.getNativeBuffer();
                                            outputStream.write(buffer, 0, chunk.length());
                                        } else {
                                            outputStream.write(chunk.getBytes());
                                        }
                                    } catch (IOException e) {
                                        // This will get caught by the API connector, which will abort the
                                        // connection to the back-end API.
                                        throw new RuntimeException(e);
                                    }
                                }
                            });
                            engineResult.endHandler(new IAsyncHandler<Void>() {
                                @Override
                                public void handle(Void result) {
                                    try {
                                        resp.flushBuffer();
                                    } catch (IOException e) {
                                        // This will get caught by the API connector, which will abort the
                                        // connection to the back-end API.
                                        throw new RuntimeException(e);
                                    } finally {
                                        latch.countDown();
                                    }
                                }
                            });
                        } catch (IOException e) {
                            // this would mean we couldn't get the output stream from the response, so we
                            // need to abort the engine result (which will let the back-end connection
                            // close down).
                            engineResult.abort(e);
                            latch.countDown();
                            throw new RuntimeException(e);
                        }
                    } else {
                        writeFailure(finalRequest, resp, engineResult.getPolicyFailure());
                        latch.countDown();
                    }
                } else {
                    writeError(finalRequest, resp, asyncResult.getError());
                    latch.countDown();
                }
            }
        });
        executor.streamHandler(new IAsyncHandler<ISignalWriteStream>() {
            @Override
            public void handle(ISignalWriteStream connectorStream) {
                try {
                    final InputStream is = req.getInputStream();
                    ByteBuffer buffer = new ByteBuffer(2048);
                    int numBytes = buffer.readFrom(is);
                    while (numBytes != -1) {
                        connectorStream.write(buffer);
                        numBytes = buffer.readFrom(is);
                    }
                    connectorStream.end();
                } catch (Throwable e) {
                    connectorStream.abort(e);
                }
            }
        });
        executor.execute();
        try { latch.await(); } catch (InterruptedException e) { }
    }
734841
public final void doWork(final HttpServletRequest pReq,
    final HttpServletResponse pResp) throws ServletException, IOException {
    pReq.setCharacterEncoding("UTF-8");
    pResp.setCharacterEncoding("UTF-8");
    IFactoryAppBeans factoryAppBeans = null;
    try {
      HashMap<String, Object> reqVars = new HashMap<String, Object>();
      factoryAppBeans = (IFactoryAppBeans) getServletContext()
          .getAttribute("IFactoryAppBeans");
      HttpRequestData requestData = new HttpRequestData(pReq, pResp);
      requestData.setAttribute("reqVars", reqVars);
      IHandlerRequest hndlI18nRequest = (IHandlerRequest)
        factoryAppBeans.lazyGet("hndlI18nRequest");
      hndlI18nRequest.handle(reqVars, requestData);
      IMngSoftware mngSoftware = (IMngSoftware) factoryAppBeans
        .lazyGet("IMngSoftware");
      ISrvI18n srvI18n = (ISrvI18n) factoryAppBeans.lazyGet("ISrvI18n");
      UtlJsp utlJsp = (UtlJsp) factoryAppBeans.lazyGet("UtlJsp");
      String dbgShStr = pReq.getParameter("dbgSh");
      if (dbgShStr != null) {
        mngSoftware.setDbgSh(Boolean.valueOf(dbgShStr));
      }
      String dbgFlStr = pReq.getParameter("dbgFl");
      if (dbgFlStr != null) {
        mngSoftware.setDbgFl(Integer.parseInt(dbgFlStr));
      }
      String dbgClStr = pReq.getParameter("dbgCl");
      if (dbgClStr != null) {
        mngSoftware.setDbgCl(Integer.parseInt(dbgClStr));
      }
      pReq.setAttribute("mngSoftware", mngSoftware);
      pReq.setAttribute("srvI18n", srvI18n);
      pReq.setAttribute("utlJsp", utlJsp);
      String nmRnd = pReq.getParameter("nmRnd");
      String path = dirJsp + nmRnd + ".jsp";
      RequestDispatcher rd = getServletContext().getRequestDispatcher(path);
      rd.include(pReq, pResp);
    } catch (Exception e) {
      if (factoryAppBeans != null) {
        ILog logger = null;
        try {
          logger = (ILog) factoryAppBeans.lazyGet("ILog");
        } catch (Exception e1) {
          e1.printStackTrace();
        }
        if (logger != null) {
          logger.error(null, getClass(), "WORK", e);
        } else {
          e.printStackTrace();
        }
      } else {
        e.printStackTrace();
      }
      if (e instanceof ExceptionWithCode) {
        pReq.setAttribute("error_code",
          ((ExceptionWithCode) e).getCode());
        pReq.setAttribute("short_message",
          ((ExceptionWithCode) e).getShortMessage());
      } else {
        pReq.setAttribute("error_code",
          HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      }
      pReq.setAttribute("javax.servlet.error.status_code",
        HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      pReq.setAttribute("javax.servlet.error.exception", e);
      pReq.setAttribute("javax.servlet.error.request_uri",
        pReq.getRequestURI());
      pReq.setAttribute("javax.servlet.error.servlet_name", this.getClass()
        .getCanonicalName());
      pResp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
  }
336549
@Override
    protected void service(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
	// get out Stream

	// pic
	String[] arrPath = (req.getServletPath()).split("\\.");
	String pic = PIC_SOURCE + "404.gif";
	if (arrPath.length >= 3) {
	    pic = PIC_SOURCE + ((arrPath[arrPath.length - 3] + "." + arrPath[arrPath.length - 2]).replaceFirst("/", ""));

	    // mime type
	    String mime = "image/" + arrPath[arrPath.length - 2];
	    ReqRspUtil.setContentType(rsp, mime);
	}

	// write data from pic input to response output
	OutputStream os = null;
	InputStream is = null;
	try {
	    os = rsp.getOutputStream();
	    is = getClass().getResourceAsStream(pic);
	    if (is == null) {
		is = getClass().getResourceAsStream(PIC_SOURCE + "404.gif");
	    }

	    byte[] buf = new byte[4 * 1024];
	    int nread = 0;
	    while ((nread = is.read(buf)) >= 0) {
		os.write(buf, 0, nread);
	    }
	}
	catch (FileNotFoundException e) {}
	catch (IOException e) {}
	finally {
	    IOUtil.closeEL(is, os);
	}
    }
615268
function handler(req, res) {

  var parsedUrl = url.parse(req.url)
  var callback = qs.parse(parsedUrl.query).callback
  var filename = decodeURI(parsedUrl.path.substr(1).split('?')[0])
  var basename = path.basename(filename.split('?')[0])
  var extname = path.extname(basename)
  var response = reswrap(res);
  var notfound = function() {
    response.writeHead(404, 'text').end('');
  };

  if (req.method === 'GET' && parsedUrl.pathname === '/jsonp-request') {
    if (!!exitCountdown) {
      exitCountdown.restart();
    }

    response
      .writeHead(200, 'js')
      .end(callback +'('+ R.get('stamp') +')');

    return;
  }

  var serve;
  if (/^\/template/.test(parsedUrl.pathname)) {
    serve = check(join(__dirname, '..', filename))
  } else if (/^\/node_modules/.test(parsedUrl.pathname)) {
    serve = check(join(__dirname, '..', filename))
  }
  if (serve) {
    serve.pass(function(name, type) {
      response
        .writeHead(200, extname.substr(1))
        .pipeWith(fs.createReadStream(
          path.resolve(name)
        ))
    }).fail(notfound);
    return;
  }

  if (/^\.(md|mkd|markdown|html)$/.test(extname)) {
    check(filename)
      .pass(function() {
        response
          .writeHead(200, 'html')
          .end(template.render({
            title: basename,
            highlight: R.get('highlight') || 'default',
            theme: getTheme(R.get('css')),
            width: R.get('width'),
            body: parser.parse(read(path.resolve(filename)))
          }));
      }).fail(notfound);

    return;
  }

  // Image or some other resources.
  check(filename)
    .pass(function(name) {
      response
        .writeHead(200, name)
        .pipeWith(fs.createReadStream(name));
    }).fail(notfound)
}
329820
private String getRequestURI(final HttpServletRequest request) {
        String ret = (String) request.getAttribute(Keys.HttpRequest.REQUEST_URI);
        if (StringUtils.isBlank(ret)) {
            ret = request.getRequestURI();
        }

        return ret;
    }
336086
protected String getStateQueryParam(HttpServletRequest req, HttpServletResponse resp){
        return String.valueOf(System.currentTimeMillis());
    }
527378
@Override
    public void service(final ServletRequest req, final ServletResponse resp) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        final String beanName = request.getPathInfo().substring(1); // remove "/"
        htorp.process(beanName, request, response);
    }
926023
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        PrintWriter out;
        String  title = "Index of ";
        String dirName = (String)req.getAttribute("com.ibm.servlet.engine.webapp.dir.browsing.path");
        String reqURI = (String)req.getAttribute("com.ibm.servlet.engine.webapp.dir.browsing.uri");

        // PK81387 Start

        //I believe dirName is now the local dir, not the file system path
        File dir = null;
        URL dirURL = null;
        String dirNameFileSystemPath = req.getRealPath(dirName);
        //this is a servlet, we only have access to the ServletContextFacade
        ServletContext context = getServletConfig().getServletContext();   
        boolean fileSystem = false;
        //dirNameFileSystemPath!=null is not a good enough check to determine if you're in a container
        //if we have a container and there have been jsps compiled, it gives you the directory in the workarea
        if (dirNameFileSystemPath!=null) {
            fileSystem = true;
            dirName=dirNameFileSystemPath;
            dir = new File(dirNameFileSystemPath);

            // get path to war directory
            String contextRealPath = context.getRealPath("/");
            
            int idx=dirName.lastIndexOf(contextRealPath);
            
            if (idx!=-1) {
            	// subtract the war directory from teh reqiested directory
            	String matchString=dirName.substring(idx+contextRealPath.length());
            	
            	matchString=matchString.replace(File.separator,"/");
            	
            	// Ensure matchString starts with "/" so WSUtil.resolveURI processes leading "."s
            	if (!matchString.startsWith("/")) {
            	   matchString="/"+matchString;
            	}
            	
            	// remove a trailing "/" so tthat uriCaseCheck does a vlaid check.
            	if (matchString.endsWith("/")) {
            		matchString=matchString.substring(0, matchString.length()-1);
            	}
            	     
            	// checkWEB-INF unless esposeWebInfoOnDispatch is set and we are in a dispatched request
            	boolean checkWEBINF = !WCCustomProperties.EXPOSE_WEB_INF_ON_DISPATCH || (req.getAttribute(WebAppRequestDispatcher.DISPATCH_NESTED_ATTR)==null) ;
            	
            	try {
            		
            		if (!com.ibm.wsspi.webcontainer.util.FileSystem.uriCaseCheck(dir, matchString,checkWEBINF))
            		{
                        resp.sendError(404, nls.getString("File.not.found", "File not found"));
                        return;
            		}	
            	} catch (java.lang.IllegalArgumentException exc) {
            		// Must be traversing back directories
                    resp.sendError(404, nls.getString("File.not.found", "File not found"));
                    return;
            	}
             } else {
                 // Must be traversing back directories
                 //dirNameFileSystemPath was normalized in Liberty, whereas in tWAS it contained the root path followed by whatever was entered
                 resp.sendError(404, nls.getString("File.not.found", "File not found"));
                 return;
             }
        }
        else { //container
            dirURL = context.getResource(dirName);
            if (dirURL == null) {
                resp.sendError(404, nls.getString("File.not.found", "File not found"));
                return;
            }
        }
            // PK81387 End	
            if (!reqURI.endsWith("/"))
                reqURI += '/';
    
            title += reqURI;
    
            // make sure we can access it
            if (fileSystem && !dir.canRead())
                resp.sendError(404, nls.getString("File.not.found", "File not found"));
        // set the content type
		// set the content type as UTF-8 as filenames are encoded in UTF-8
        resp.setContentType("text/html; charset=UTF-8");

        // write the output
        out = resp.getWriter();

        out.println("<HTML><HEAD><TITLE>");
        out.println(title);
        out.println("</TITLE></HEAD><BODY>");
        out.println("<H1 align=\"left\">" + title + "</H1>");
        out.println("<HR size=\"3\"><TABLE cellpadding=\"2\"><TBODY><TR bgcolor=\"#d7ffff\">");

        // output the table headers
        out.println("<TH width=\"250\" nowrap><P align=\"left\">Name</P></TH>");
        out.println("<TH width=\"250\" nowrap><P align=\"left\">Last Modified</P></TH>");
        out.println("<TH width=\"150\" nowrap><P align=\"left\">Size</P></TH>");
        out.println("<TH width=\"300\" nowrap><P align=\"left\">Description</P></TH></TR>");

        // output a row for each file in the directory
        if (fileSystem) {
            fillTableRows(dir, reqURI, out);
        } else {
            fillTableRows(context, dirName, reqURI, out);
        }

        // finish the page
        out.println("</TBODY></TABLE></BODY></HTML>");

        // close it up
        out.close();
    }
575905
public static String reconstructURL (HttpServletRequest req)
    {
        StringBuffer buf = req.getRequestURL();
        @SuppressWarnings("unchecked") Map<String, String[]> map = req.getParameterMap();
        if (map.size() > 0) {
            buf.append("?");
            for (Map.Entry<String, String[]> entry : map.entrySet()) {
                if (buf.charAt(buf.length()-1) != '?') {
                    buf.append("&");
                }
                buf.append(entry.getKey()).append("=");
                String[] values = entry.getValue();
                if (values.length == 1) {
                    buf.append(values[0]);
                } else {
                    buf.append("(");
                    for (int ii = 0; ii < values.length; ii++) {
                        if (ii > 0) {
                            buf.append(", ");
                        }
                        buf.append(values[ii]);
                    }
                    buf.append(")");
                }
            }
        }
        return buf.toString();
    }
465187
function (req, res) {
		LOG.warn('handle_request');

		// attach custom res methods (borrowed from express)
		res = UTIL.mixin(res, response);

		LOG.sys('HTTP req received, header', 'SR.REST');
		LOG.sys(req.headers, 'SR.REST');
		
		var content_type = req.headers['content-type'];

		// NOTE: multi-part needs to be handled first, because req.on('data') will not be able to process correctly
		if (typeof content_type === 'string' && content_type.startsWith('multipart/form-data; boundary=')) { 
			LOG.warn('parsing form request...', 'SR.REST');
			route(req, res);
			return;
		}
		
		// temp buffer for incoming request
		var data = '';
		var JSONobj = undefined;
		
		req.on('data', function (chunk) {
			data += chunk;
		});

		req.on('end', function () {
			
			var JSONobj = undefined;
			
			try {
				if (data !== '') {
						
					if (content_type.startsWith('application/x-www-form-urlencoded')) {
						JSONobj = qs.parse(data);
					} else if (content_type.startsWith('application/json')) {
						JSONobj = UTIL.convertJSON(decodeURIComponent(data));
					} else if (content_type.startsWith('application/sdp')) {
						JSONobj = data;
					} else {
						var msg = 'content type not known: ' + content_type;
						LOG.warn(msg, 'SR.REST');
						SR.REST.reply(res, msg);
						//res.writeHead(200, {'Content-Type': 'text/plain'});
						//res.end(msg);
						return;
					}
				}
			} catch (e) {
				var msg = 'JSON parsing error for data: ' + data + '\n content_type: ' + content_type;
				LOG.error(msg, 'SR.REST');
				//res.writeHead(200, {'Content-Type': 'text/plain'});
				//res.end(msg);
				SR.REST.reply(res, msg);
				return;
			}

			route(req, res, JSONobj);
		})
	}