Example usage for jdk.nashorn.api.scripting ScriptObjectMirror equals

List of usage examples for jdk.nashorn.api.scripting ScriptObjectMirror equals

Introduction

In this page you can find the example usage for jdk.nashorn.api.scripting ScriptObjectMirror equals.

Prototype

@Override
    public boolean equals(final Object other) 

Source Link

Usage

From source file:com.bytelightning.opensource.pokerface.RequestHandler.java

License:Open Source License

/**
 * {@inheritDoc}//  ww w.ja  v a 2s.c o m
 * Main entry point of a client request into this server.
 * This method creates a unique id for the request / response transaction, looks for a matching javascript endpoint (which if found is given an opportunity to inspect the request).
 * If an endpoint is found and it wishes to handle the request, an appropriate <code>HttpAsyncRequestConsumer<ResponseProducer></code> is returned to make that happen.
 * Otherwise the request (which may have been modified by the endpoint) is asynchronously sent off to a matching remote Target via <code>RequestForTargetConsumer</code>.
 */
@SuppressWarnings("unchecked")
@Override
public HttpAsyncRequestConsumer<ResponseProducer> processRequest(HttpRequest request, HttpContext context) {
    // Create an internal id for this request.
    String txId = String.format("%08X", idCounter.getAndIncrement());
    context.setAttribute("pokerface.txId", txId);
    boolean requestIsFromScript = false;
    HttpContext scriptContext = null;
    ScriptObjectMirror scriptEndpoint = null;
    RequestLine requestLine = request.getRequestLine();
    String uriStr = requestLine.getUri();
    int queryPos = uriStr.lastIndexOf('?');
    if (queryPos > 0)
        uriStr = uriStr.substring(0, queryPos);
    int anchorPos = uriStr.lastIndexOf('#'); // You could have an anchor without a query
    if (anchorPos > 0)
        uriStr = uriStr.substring(0, anchorPos);
    context.setAttribute("pokerface.uripath", uriStr);

    // See if this is a request for one of our static resources.
    if (staticFilesPath != null) {
        String method = requestLine.getMethod();
        if (method.equals("GET") || method.equals("HEAD")) {
            try {
                Path rsrcPath = staticFilesPath.resolve(uriStr.replaceAll("\\.\\./", "/").substring(1));
                if (Files.exists(rsrcPath) && Files.isRegularFile(rsrcPath))
                    return new RequestForFileConsumer(context, rsrcPath.toFile());
            } catch (Exception ex) {
                Logger.warn("Error resolving URI path", ex);
            }
        }
    }

    BufferIOController requestBuffer = new BufferIOController(bufferPool);
    BufferIOController responseBuffer = new BufferIOController(bufferPool);

    // If script endpoints are configured, look for the closest match (if any).
    if (scripts != null) {
        uriStr = uriStr.toLowerCase();
        Entry<String, ScriptObjectMirror> entry = scripts.floorEntry(uriStr);
        if ((entry != null) && uriStr.startsWith(entry.getKey())) {
            // We found a matching script, so give it an opportunity to inspect the request.
            StringBuilder sb = new StringBuilder();
            RequestLine reqLine = request.getRequestLine();
            sb.append(reqLine.getMethod());
            sb.append(" ");
            sb.append(reqLine.getUri());
            sb.append(" being inspected by ");
            String logPrefix = sb.toString();
            scriptContext = new BasicHttpContext(context);
            scriptContext.setAttribute("pokerface.scriptHelper",
                    new ScriptHelperImpl(request, context, bufferPool));
            scriptContext.setAttribute("pokerface.endpoints", scripts);
            scriptContext.setAttribute("pokerface.scriptLogger", ScriptHelper.ScriptLogger);
            //FIXME: Test out the recursively higher script selection.
            //FIXME: Add ignore of # directories (don't forget to update the file watcher to ignore them as well)
            // Call recursively higher (closer to the root) scripts until one is interested.
            Object scriptResult = null;
            while (true) {
                sb.setLength(0);
                sb.append(logPrefix);
                String key = entry.getKey();
                sb.append(key);
                if (key.endsWith("/"))
                    sb.append("?");
                sb.append(".js");
                Logger.info(sb.toString());
                scriptEndpoint = entry.getValue();
                scriptResult = scriptEndpoint.callMember("inspectRequest", request, scriptContext);
                scriptResult = transformScriptInspectionResult(request, scriptResult);
                if (scriptResult == null) {
                    if (uriStr.length() > 1) {
                        int lastSlash = uriStr.lastIndexOf('/', uriStr.length());
                        if (lastSlash >= 0) {
                            uriStr = uriStr.substring(0, lastSlash + 1); // Add a slash to see if there is a directory script
                            entry = scripts.floorEntry(uriStr);
                            if ((entry != null) && uriStr.startsWith(entry.getKey()))
                                continue;
                            if (lastSlash > 0) {
                                uriStr = uriStr.substring(0, uriStr.length() - 1); // Drop the slash and try again.
                                entry = scripts.floorEntry(uriStr);
                                if ((entry != null) && uriStr.startsWith(entry.getKey()))
                                    continue;
                            }
                        }
                    }
                }
                break;
            }
            // Process the scripts response (if any).
            if (scriptResult != null) {
                if (scriptResult instanceof HttpAsyncRequestConsumer<?>)
                    return (HttpAsyncRequestConsumer<ResponseProducer>) scriptResult;
                else if ((scriptResult instanceof ScriptObjectMirror) && scriptEndpoint.equals(scriptResult)) // The script wants to handle the request itself.
                    return new RequestForScriptConsumer(scriptContext, requestBuffer,
                            new ScriptResponseProducer(scriptEndpoint, request, scriptContext, responseBuffer));
                else {
                    // The script wants to pass along a modified Request to the target
                    assert scriptResult instanceof HttpRequest;
                    request = (HttpRequest) scriptResult;
                    requestIsFromScript = true;
                }
            }
            // else no script cared about this request, so just fall through to normal processing.
        }
    }
    // Create a AbsClientRequestConsumer that can proxy to the remote Target.
    return new RequestForTargetConsumer(scriptContext == null ? context : scriptContext, executor, connPool,
            patternTargetMapping, requestIsFromScript ? dynamicHostMap : null, request, requestBuffer,
            responseBuffer, scriptEndpoint);
}