Add an 'OPTIONS' method supported on all routes for the pre-flight CORS request.

@param server a RestExpress server instance.
121
private void addPreflightOptionsRequestSupport(RestExpress server, CorsOptionsController corsOptionsController)
    {
	    RouteBuilder rb;

	    for (String pattern : methodsByPattern.keySet())
	    {
	    	rb = server.uri(pattern, corsOptionsController)
		    	.action("options", HttpMethod.OPTIONS)
		    	.noSerialization()
		    	// Disable both authentication and authorization which are usually use header such as X-Authorization.
		    	// When browser does CORS preflight with OPTIONS request, such headers are not included.
		    	.flag(Flags.Auth.PUBLIC_ROUTE)
		    	.flag(Flags.Auth.NO_AUTHORIZATION);

	    	for (String flag : flags)
	    	{
	    		rb.flag(flag);
	    	}

	    	for (Entry<String, Object> entry : parameters.entrySet())
	    	{
	    		rb.parameter(entry.getKey(), entry.getValue());
	    	}

	    	routeBuilders.add(rb);
	    }
    }
542231
protected function preFlightOptions(Request $request, string $allowMethods = 'OPTIONS'): ?JsonResponse
    {
        if (strtolower($request->getMethod()) === self::OPTIONS_CALL) {
            $origin = $request->headers->get('Origin');
            return new JsonResponse([], JsonResponse::HTTP_OK, [
                'Access-Control-Allow-Origin' => $origin ?: '*',
                'Access-Control-Allow-Methods' => $allowMethods,
                'Access-Control-Allow-Credentials' => 'true'
            ]);
        }

        return null;
    }
187086
private function buildSettings(ServerRequestInterface $request, ResponseInterface $response): CorsSettings
    {
        $settings = new CorsSettings;

        $origin = array_fill_keys((array) $this->options["origin"], true);
        $settings->setRequestAllowedOrigins($origin);

        if (is_callable($this->options["methods"])) {
            $methods = (array) $this->options["methods"]($request, $response);
        } else {
            $methods = $this->options["methods"];
        }
        $methods = array_fill_keys($methods, true);
        $settings->setRequestAllowedMethods($methods);

        $headers = array_fill_keys($this->options["headers.allow"], true);
        $headers = array_change_key_case($headers, CASE_LOWER);
        $settings->setRequestAllowedHeaders($headers);

        $headers = array_fill_keys($this->options["headers.expose"], true);
        $settings->setResponseExposedHeaders($headers);

        $settings->setRequestCredentialsSupported($this->options["credentials"]);

        if (is_string($this->options["origin.server"])) {
            $settings->setServerOrigin($this->options["origin.server"]);
        }

        $settings->setPreFlightCacheMaxAge($this->options["cache"]);

        return $settings;
    }
207727
private void setCorsHeader(HttpServletRequest pReq, HttpServletResponse pResp) {
        String origin = requestHandler.extractCorsOrigin(pReq.getHeader("Origin"));
        if (origin != null) {
            pResp.setHeader("Access-Control-Allow-Origin", origin);
            pResp.setHeader("Access-Control-Allow-Credentials","true");
        }
    }
672091
private HttpResponse handleCorsPreflight(ServiceRequestContext ctx, HttpRequest req) {
        final HttpHeaders headers = HttpHeaders.of(HttpStatus.OK);
        final CorsPolicy policy = setCorsOrigin(ctx, req, headers);
        if (policy != null) {
            policy.setCorsAllowMethods(headers);
            policy.setCorsAllowHeaders(headers);
            policy.setCorsAllowCredentials(headers);
            policy.setCorsMaxAge(headers);
            policy.setCorsPreflightResponseHeaders(headers);
        }

        return HttpResponse.of(headers);
    }
494680
public function options( ServerRequestInterface $request, ResponseInterface $response )
	{
		return $this->client->options( $request, $response );
	}
374510
private void configureCors(Environment environment) {
        Dynamic filter = environment.servlets().addFilter("CORS", CrossOriginFilter.class);
        filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
        filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,PUT,POST,DELETE,OPTIONS");
        filter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
        filter.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*");
        filter.setInitParameter("allowedHeaders", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin");
        filter.setInitParameter("allowCredentials", "true");
    }
596604
@OPTIONS
    @Timed
    public void options(@Suspended final AsyncResponse response, @Context final Request request,
            @Context final UriInfo uriInfo, @Context final HttpHeaders headers) {
        final TrellisRequest req = new TrellisRequest(request, uriInfo, headers);
        final String urlBase = getBaseUrl(req);
        final IRI identifier = rdf.createIRI(TRELLIS_DATA_PREFIX + req.getPath());
        final OptionsHandler optionsHandler = new OptionsHandler(req, trellis, req.getVersion() != null, urlBase);

        fetchTrellisResource(identifier, req.getVersion()).thenApply(optionsHandler::initialize)
            .thenApply(optionsHandler::ldpOptions).thenApply(ResponseBuilder::build)
            .exceptionally(this::handleException).thenApply(response::resume);
    }
484418
private void addPostParams(final Request request) {
        if (url != null) {
            request.addPostParam("Url", url.toString());
        }

        if (method != null) {
            request.addPostParam("Method", method.toString());
        }

        if (status != null) {
            request.addPostParam("Status", status.toString());
        }

        if (fallbackUrl != null) {
            request.addPostParam("FallbackUrl", fallbackUrl.toString());
        }

        if (fallbackMethod != null) {
            request.addPostParam("FallbackMethod", fallbackMethod.toString());
        }

        if (statusCallback != null) {
            request.addPostParam("StatusCallback", statusCallback.toString());
        }

        if (statusCallbackMethod != null) {
            request.addPostParam("StatusCallbackMethod", statusCallbackMethod.toString());
        }
    }
539586
public void document_cors_POST(String origin) throws IOException {
		String qPath = "/store/document/cors";
		StringBuilder sb = path(qPath);
		HashMap<String, Object>o = new HashMap<String, Object>();
		addBody(o, "origin", origin);
		exec(qPath, "POST", sb.toString(), o);
	}
1151527
protected base_response add_resource(nitro_service service,options option)  throws Exception
	{
		if (!service.isLogin() && !this.get_object_type().equals("login"))
			service.login();
		String sessionid = service.get_sessionid();
		String request = resource_to_string(service, sessionid, option);
		return post_data(service,request);
	}
1123948
function resolveServer(path, options) {
    if (options === void 0) { options = {}; }
    var serverUrl = options.serverUrl || init.initOptions.serverUrl;
    if (path) {
        if (serverUrl) {
            path = url.resolve(serverUrl, path);
        }
    }
    else {
        path = serverUrl;
    }
    return url.resolve(path, '/');
}
562717
public final void addServer(final String server, final int port, int weight) throws IOException {
    if (weight <= 0) {
      throw new IllegalArgumentException("weight<=0");
    }
    this.checkServerPort(server, port);
    this.connect(new InetSocketAddressWrapper(this.newSocketAddress(server, port),
        this.serverOrderCount.incrementAndGet(), weight, null));
  }
1028850
function RequestOptions(opts) {
        if (opts === void 0) { opts = {}; }
        var method = opts.method, headers = opts.headers, body = opts.body, url = opts.url, search = opts.search, params = opts.params, withCredentials = opts.withCredentials, responseType = opts.responseType;
        this.method = method != null ? normalizeMethodName(method) : null;
        this.headers = headers != null ? headers : null;
        this.body = body != null ? body : null;
        this.url = url != null ? url : null;
        this.params = this._mergeSearchParams(params || search);
        this.withCredentials = withCredentials != null ? withCredentials : null;
        this.responseType = responseType != null ? responseType : null;
    }
613098
function createEndpointFromObject(path, query, body) {
  // OPTIONS gives server permission to use CORS
  server.createRoute({
    request: {
        url: path,
        query: query || {},
        method: 'options',
    },
    response: {
        code: 200,
        delay: config.latency,
        body: {},
        headers: {
          'Access-Control-Allow-Origin': config.allowOrigin,
          // allow several methods since some endpoints are writable
          'Access-Control-Allow-Methods': 'GET, PUT, POST',
          'Access-Control-Allow-Credentials': 'true'
        }
    }
  });
  return server.get(path)
               .query(query)
               .responseHeaders({
                 'Access-Control-Allow-Origin': config.allowOrigin,
                 'Access-Control-Allow-Methods': 'GET, PUT, POST',
                 'Access-Control-Allow-Credentials': 'true'
               })
               .body(body)
               .delay(config.latency);
}
1085213
function addApiRoutes(opts) {
    var resources   = this.pancakes.cook('resources', null);
    var apiPrefix   = opts.apiPrefix;
    var server      = opts.server;
    var me          = this;
    var cors = {
        origin:         opts.hosts || [],
        headers:        ['Accept', 'Accept-Version', 'Content-Type', 'Api-Version', 'X-Requested-With', 'Authorization'],
        credentials:    true
    };

    _.each(resources, function (resource) {
        _.each(resource.api, function (methodInfo, httpMethod) {
            _.each(methodInfo, function (operation, path) {

                // if path includes {_id} convert to {_id?} so optional
                // this will allow both /users/someid and /users to work
                // we want this because pancakes handles param validation
                // only do this if path without {_id} is not already defined
                var lenWithoutId = path.length - 6;
                var pathWithoutId = path.substring(0, lenWithoutId);
                if (path.substring(lenWithoutId) === '/{_id}' && !methodInfo[pathWithoutId]) {
                    path = pathWithoutId + '/{_id?}';
                }

                // if the operation is a string, then it is the name of the handler method
                if (_.isString(operation)) {
                    server.route({
                        method:             httpMethod,
                        path:               apiPrefix + path,
                        config: {
                            cors:           cors,
                            handler:        me.getApiRouteHandler(resource, operation)
                        }
                    });
                }

                // else if object with type stream, need to use a slightly different call to server.route
                else if (_.isObject(operation) && operation.type === 'stream' && operation.operation) {
                    server.route({
                        method:             httpMethod,
                        path:               apiPrefix + path,
                        config: {
                            payload: {
                                maxBytes:   209715200,
                                output:     'stream',
                                parse:      true
                            },
                            cors:           cors,
                            handler:        me.getApiRouteHandler(resource, operation.operation)
                        }
                    });
                }
                // or xml...
                else if (_.isObject(operation) && operation.type === 'xml' && operation.operation) {
                    server.route({
                        method:             httpMethod,
                        path:               apiPrefix + path,
                        config: {
                            cors:           cors,
                            handler:        me.getApiRouteHandler(resource, operation.operation, 'application/xml; charset=utf-8')
                        }
                    });
                }

                // else error
                else {
                    throw new Error('Invalid type of operation for ' + resource.name + ' ' + path);
                }
            });
        });
    });

    server.on('response', function (request) {
        // careful because we don't want to screw up all/any requests...
        if ( request.response && request.response.statusCode && request.response.statusCode > 399 && request.method
                && request.method.toUpperCase && request.url && request.url.path ) {
            var lapse = -1;
            if ( request.info && request.info.responded && request.info.received ) {
                lapse = request.info.responded - request.info.received;
            }
            var msg = request.method.toUpperCase() + ' ' + request.url.path + ' -> '
                + request.response.statusCode + ' ' + '(' + lapse + 'ms)';
            if ( request.info && request.info.referrer && request.info.referrer.length ) {
                msg += ' ref: ' + request.info.referrer;
            }

            /* eslint no-console:0 */
            console.log(msg);
        }
    });
}
620105
@Override
	public void doFilter(final ServletRequest servletRequest,
			final ServletResponse servletResponse,
			final FilterChain filterChain) throws IOException,
			ServletException {
		if (!(servletRequest instanceof HttpServletRequest)
				|| !(servletResponse instanceof HttpServletResponse)) {
			String message
					= "CORS doesn't support non-HTTP request or response.";
			throw new ServletException(message);
		}

		// Safe to downcast at this point.
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;

		// Determines the CORS request type.
		CORSFilter.CORSRequestType requestType = checkRequestType(request);

		// Adds CORS specific attributes to request.
		if (decorateRequest) {
			CORSFilter.decorateCORSProperties(request, requestType);
		}
		switch (requestType) {
			case SIMPLE:
				// Handles a Simple CORS request.
				this.handleSimpleCORS(request, response, filterChain);
				break;
			case ACTUAL:
				// Handles an Actual CORS request.
				this.handleSimpleCORS(request, response, filterChain);
				break;
			case PRE_FLIGHT:
				// Handles a Pre-flight CORS request.
				this.handlePreflightCORS(request, response, filterChain);
				break;
			case NOT_CORS:
				// Handles a Normal request that is not a cross-origin request.
				this.handleNonCORS(request, response, filterChain);
				break;
			default:
				// Handles a CORS request that violates specification.
				this.handleInvalidCORS(request, response, filterChain);
				break;
		}
	}