text:
/*
 * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
 * See https://github.com/openiddict/openiddict-core for more information concerning
 * the license and the contributors participating to this project.
 */

using System;
using System.Collections.Immutable;
using System.Text;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Microsoft.Extensions.Logging;
using OpenIddict.Abstractions;
using static OpenIddict.Abstractions.OpenIddictConstants;
using static OpenIddict.Server.OpenIddictServerEvents;
using static OpenIddict.Server.OpenIddictServerHandlerFilters;

namespace OpenIddict.Server
{
    public static partial class OpenIddictServerHandlers
    {
        public static class Revocation
        {
            public static ImmutableArray<OpenIddictServerHandlerDescriptor> DefaultHandlers { get; } = ImmutableArray.Create(
                /*
                 * Revocation request top-level processing:
                 */
                ExtractRevocationRequest.Descriptor,
                ValidateRevocationRequest.Descriptor,
                HandleRevocationRequest.Descriptor,
                ApplyRevocationResponse<ProcessErrorContext>.Descriptor,
                ApplyRevocationResponse<ProcessRequestContext>.Descriptor,

                /*
                 * Revocation request validation:
                 */
                ValidateTokenParameter.Descriptor,
                ValidateClientIdParameter.Descriptor,
                ValidateClientId.Descriptor,
                ValidateClientType.Descriptor,
                ValidateClientSecret.Descriptor,
                ValidateEndpointPermissions.Descriptor,
                ValidateToken.Descriptor,
                ValidateTokenType.Descriptor,
                ValidateAuthorizedParty.Descriptor,

                /*
                 * Revocation request handling:
                 */
                AttachPrincipal.Descriptor,
                RevokeToken.Descriptor,

                /*
                 * Revocation response handling:
                 */
                NormalizeErrorResponse.Descriptor);

            /// <summary>
            /// Contains the logic responsible of extracting revocation requests and invoking the corresponding event handlers.
            /// </summary>
            public class ExtractRevocationRequest : IOpenIddictServerHandler<ProcessRequestContext>
            {
                private readonly IOpenIddictServerDispatcher _dispatcher;

                public ExtractRevocationRequest([NotNull] IOpenIddictServerDispatcher dispatcher)
                    => _dispatcher = dispatcher;

                /// <summary>
                /// Gets the default descriptor definition assigned to this handler.
                /// </summary>
                public static OpenIddictServerHandlerDescriptor Descriptor { get; }
                    = OpenIddictServerHandlerDescriptor.CreateBuilder<ProcessRequestContext>()
                        .AddFilter<RequireRevocationRequest>()
                        .UseScopedHandler<ExtractRevocationRequest>()
                        .SetOrder(100_000)
                        .SetType(OpenIddictServerHandlerType.BuiltIn)
                        .Build();

                /// <summary>
                /// Processes the event.
                /// </summary>
                /// <param name="context">The context associated with the event to process.</param>
                /// <returns>
                /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
                /// </returns>
                public async ValueTask HandleAsync([NotNull] ProcessRequestContext context)
                {
                    if (context == null)
                    {
                        throw new ArgumentNullException(nameof(context));
                    }

                    var notification = new ExtractRevocationRequestContext(context.Transaction);
                    await _dispatcher.DispatchAsync(notification);

                    if (notification.IsRequestHandled)
                    {
                        context.HandleRequest();
                        return;
                    }

                    else if (notification.IsRequestSkipped)
                    {
                        context.SkipRequest();
                        return;
                    }

                    else if (notification.IsRejected)
                    {
                        context.Reject(
                            error: notification.Error ?? Errors.InvalidRequest,
                            description: notification.ErrorDescription,
                            uri: notification.ErrorUri);
                        return;
                    }

                    if (notification.Request == null)
                    {
                        throw new InvalidOperationException(new StringBuilder()
                            .Append("The revocation request was not correctly extracted. To extract revocation requests, ")
                            .Append("create a class implementing 'IOpenIddictServerHandler<ExtractRevocationRequestContext>' ")
                            .AppendLine("and register it using 'services.AddOpenIddict().AddServer().AddEventHandler()'.")
                            .ToString());
                    }

                    context.Logger.LogInformation("The revocation request was successfully extracted: {Request}.", notification.Request);
                }
            }

            /// <summary>
            /// Contains the logic responsible of validating revocation requests and invoking the corresponding event handlers.
            /// </summary>
            public class ValidateRevocationRequest : IOpenIddictServerHandler<ProcessRequestContext>
            {
                private readonly IOpenIddictServerDispatcher _dispatcher;

                public ValidateRevocationRequest([NotNull] IOpenIddictServerDispatcher dispatcher)
                    => _dispatcher = dispatcher;

                /// <summary>
                /// Gets the default descriptor definition assigned to this handler.
                /// </summary>
                public static OpenIddictServerHandlerDescriptor Descriptor { get; }
                    = OpenIddictServerHandlerDescriptor.CreateBuilder<ProcessRequestContext>()
                        .AddFilter<RequireRevocationRequest>()
                        .UseScopedHandler<ValidateRevocationRequest>()
                        .SetOrder(ExtractRevocationRequest.Descriptor.Order + 1_000)
                        .SetType(OpenIddictServerHandlerType.BuiltIn)
                        .Build();

                /// <summary>
                /// Processes the event.
                /// </summary>
                /// <param name="context">The context associated with the event to process.</param>
                /// <returns>
                /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
                /// </returns>
                public async ValueTask HandleAsync([NotNull] ProcessRequestContext context)
                {
                    if (context == null)
                    {
                        throw new ArgumentNullException(nameof(context));
                    }

                    var notification = new ValidateRevocationRequestContext(context.Transaction);
                    await _dispatcher.DispatchAsync(notification);

                    // Store the context object in the transaction so it can be later retrieved by handlers
                    // that want to access the principal without triggering a new validation process.
                    context.Transaction.SetProperty(typeof(ValidateRevocationRequestContext).FullName, notification);

                    if (notification.IsRequestHandled)
                    {
                        context.HandleRequest();
                        return;
                    }

                    else if (notification.IsRequestSkipped)
                    {
                        context.SkipRequest();
                        return;
                    }

                    else if (notification.IsRejected)
                    {
                        context.Reject(
                            error: notification.Error ?? Errors.InvalidRequest,
                            description: notification.ErrorDescription,
                            uri: notification.ErrorUri);
                        return;
                    }

                    context.Logger.LogInformation("The revocation request was successfully validated.");
                }
            }

            /// <summary>
            /// Contains the logic responsible of handling revocation requests and invoking the corresponding event handlers.
            /// </summary>
            public class HandleRevocationRequest : IOpenIddictServerHandler<ProcessRequestContext>
            {
                private readonly IOpenIddictServerDispatcher _dispatcher;

                public HandleRevocationRequest([NotNull] IOpenIddictServerDispatcher dispatcher)
                    => _dispatcher = dispatcher;

                /// <summary>
                /// Gets the default descriptor definition assigned to this handler.
                /// </summary>
                public static OpenIddictServerHandlerDescriptor Descriptor { get; }
                    = OpenIddictServerHandlerDescriptor.CreateBuilder<ProcessRequestContext>()
                        .AddFilter<RequireRevocationRequest>()
                        .UseScopedHandler<HandleRevocationRequest>()
                        .SetOrder(ValidateRevocationRequest.Descriptor.Order + 1_000)
                        .SetType(OpenIddictServerHandlerType.BuiltIn)
                        .Build();

                /// <summary>
                /// Processes the event.
                /// </summary>
                /// <param name="context">The context associated with the event to process.</param>
                /// <returns>
                /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
                /// </returns>
                public async ValueTask HandleAsync([NotNull] ProcessRequestContext context)
                {
                    if (context == null)
                    {
                        throw new ArgumentNullException(nameof(context));
                    }

                    var notification = new HandleRevocationRequestContext(context.Transaction);
                    await _dispatcher.DispatchAsync(notification);

                    if (notification.IsRequestHandled)
                    {
                        context.HandleRequest();
                        return;
                    }

                    else if (notification.IsRequestSkipped)
                    {
                        context.SkipRequest();
                        return;
                    }

                    else if (notification.IsRejected)
                    {
                        context.Reject(
                            error: notification.Error ?? Errors.InvalidRequest,
                            description: notification.ErrorDescription,
                            uri: notification.ErrorUri);
                        return;
                    }

                    context.Response = new OpenIddictResponse();
                }
            }

            /// <summary>
            /// Contains the logic responsible of processing sign-in responses and invoking the corresponding event handlers.
            /// </summary>
            public class ApplyRevocationResponse<TContext> : IOpenIddictServerHandler<TContext> where TContext : BaseRequestContext
            {
                private readonly IOpenIddictServerDispatcher _dispatcher;

                public ApplyRevocationResponse([NotNull] IOpenIddictServerDispatcher dispatcher)
                    => _dispatcher = dispatcher;

                /// <summary>
                /// Gets the default descriptor definition assigned to this handler.
                /// </summary>
                public static OpenIddictServerHandlerDescriptor Descriptor { get; }
                    = OpenIddictServerHandlerDescriptor.CreateBuilder<TContext>()
                        .AddFilter<RequireRevocationRequest>()
                        .UseScopedHandler<ApplyRevocationResponse<TContext>>()
                        .SetOrder(int.MaxValue - 100_000)
                        .SetType(OpenIddictServerHandlerType.BuiltIn)
                        .Build();

                /// <summary>
                /// Processes the event.
                /// </summary>
                /// <param name="context">The context associated with the event to process.</param>
                /// <returns>
                /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
                /// </returns>
                public async ValueTask HandleAsync([NotNull] TContext context)
                {
                    if (context == null)
                    {
                        throw new ArgumentNullException(nameof(context));
                    }

                    var notification = new ApplyRevocationResponseContext(context.Transaction);
                    await _dispatcher.DispatchAsync(notification);

                    if (notification.IsRequestHandled)
                    {
                        context.HandleRequest();
                        return;
                    }

                    else if (notification.IsRequestSkipped)
                    {
                        context.SkipRequest();
                        return;
                    }

                    throw new InvalidOperationException(new StringBuilder()
                        .Append("The revocation response was not correctly applied. To apply revocation responses, ")
                        .Append("create a class implementing 'IOpenIddictServerHandler<ApplyRevocationResponseContext>' ")
                        .AppendLine("and register it using 'services.AddOpenIddict().AddServer().AddEventHandler()'.")
                        .ToString());
                }
            }

            /// <summary>
            /// Contains the logic responsible of rejecting revocation requests that don't specify a token.
            /// </summary>
            public class ValidateTokenParameter : IOpenIddictServerHandler<ValidateRevocationRequestContext>
            {
                /// <summary>
                /// Gets the default descriptor definition assigned to this handler.
                /// </summary>
                public static OpenIddictServerHandlerDescriptor Descriptor { get; }
                    = OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateRevocationRequestContext>()
                        .UseSingletonHandler<ValidateTokenParameter>()
                        .SetOrder(int.MinValue + 100_000)
                        .SetType(OpenIddictServerHandlerType.BuiltIn)
                        .Build();

                /// <summary>
                /// Processes the event.
                /// </summary>
                /// <param name="context">The context associated with the event to process.</param>
                /// <returns>
                /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
                /// </returns>
                public ValueTask HandleAsync([NotNull] ValidateRevocationRequestContext context)
                {
                    if (context == null)
                    {
                        throw new ArgumentNullException(nameof(context));
                    }

                    // Reject revocation requests missing the mandatory token parameter.
                    if (string.IsNullOrEmpty(context.Request.Token))
                    {
                        context.Logger.LogError("The revocation request was rejected because the token was missing.");

                        context.Reject(
                            error: Errors.InvalidRequest,
                            description: "The mandatory 'token' parameter is missing.");

                        return default;
                    }

                    return default;
                }
            }

            /// <summary>
            /// Contains the logic responsible of rejecting revocation requests that don't specify a client identifier.
            /// </summary>
            public class ValidateClientIdParameter : IOpenIddictServerHandler<ValidateRevocationRequestContext>
            {
                /// <summary>
                /// Gets the default descriptor definition assigned to this handler.
                /// </summary>
                public static OpenIddictServerHandlerDescriptor Descriptor { get; }
                    = OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateRevocationRequestContext>()
                        .UseSingletonHandler<ValidateClientIdParameter>()
                        .SetOrder(ValidateTokenParameter.Descriptor.Order + 1_000)
                        .SetType(OpenIddictServerHandlerType.BuiltIn)
                        .Build();

                /// <summary>
                /// Processes the event.
                /// </summary>
                /// <param name="context">The context associated with the event to process.</param>
                /// <returns>
                /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
                /// </returns>
                public ValueTask HandleAsync([NotNull] ValidateRevocationRequestContext context)
                {
                    if (context == null)
                    {
                        throw new ArgumentNullException(nameof(context));
                    }

                    // At this stage, reject the revocation request unless the client identification requirement was disabled.
                    if (!context.Options.AcceptAnonymousClients && string.IsNullOrEmpty(context.ClientId))
                    {
                        context.Logger.LogError("The revocation request was rejected because the mandatory 'client_id' was missing.");

                        context.Reject(
                            error: Errors.InvalidClient,
                            description: "The mandatory 'client_id' parameter is missing.");

                        return default;
                    }

                    return default;
                }
            }

            /// <summary>
            /// Contains the logic responsible of rejecting revocation requests that use an invalid client_id.
            /// Note: this handler is not used when the degraded mode is enabled.
            /// </summary>
            public class ValidateClientId : IOpenIddictServerHandler<ValidateRevocationRequestContext>
            {
                private readonly IOpenIddictApplicationManager _applicationManager;

                public ValidateClientId() => throw new InvalidOperationException(new StringBuilder()
                    .AppendLine("The core services must be registered when enabling the OpenIddict server feature.")
                    .Append("To register the OpenIddict core services, reference the 'OpenIddict.Core' package ")
                    .AppendLine("and call 'services.AddOpenIddict().AddCore()' from 'ConfigureServices'.")
                    .Append("Alternatively, you can disable the built-in database-based server features by enabling ")
                    .Append("the degraded mode with 'services.AddOpenIddict().AddServer().EnableDegradedMode()'.")
                    .ToString());

                public ValidateClientId([NotNull] IOpenIddictApplicationManager applicationManager)
                    => _applicationManager = applicationManager;

                /// <summary>
                /// Gets the default descriptor definition assigned to this handler.
                /// </summary>
                public static OpenIddictServerHandlerDescriptor Descriptor { get; }
                    = OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateRevocationRequestContext>()
                        .AddFilter<RequireClientIdParameter>()
                        .AddFilter<RequireDegradedModeDisabled>()
                        .UseScopedHandler<ValidateClientId>()
                        .SetOrder(ValidateClientIdParameter.Descriptor.Order + 1_000)
                        .SetType(OpenIddictServerHandlerType.BuiltIn)
                        .Build();

                /// <summary>
                /// Processes the event.
                /// </summary>
                /// <param name="context">The context associated with the event to process.</param>
                /// <returns>
                /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
                /// </returns>
                public async ValueTask HandleAsync([NotNull] ValidateRevocationRequestContext context)
                {
                    if (context == null)
                    {
                        throw new ArgumentNullException(nameof(context));
                    }

                    // Retrieve the application details corresponding to the requested client_id.
                    // If no entity can be found, this likely indicates that the client_id is invalid.
                    var application = await _applicationManager.FindByClientIdAsync(context.ClientId);
                    if (application == null)
                    {
                        context.Logger.LogError("The revocation request was rejected because the client " +
                                                "application was not found: '{ClientId}'.", context.ClientId);

                        context.Reject(
                            error: Errors.InvalidClient,
                            description: "The specified 'client_id' parameter is invalid.");

                        return;
                    }
                }
            }

            /// <summary>
            /// Contains the logic responsible of rejecting revocation requests made by applications
            /// whose client type is not compatible with the presence or absence of a client secret.
            /// Note: this handler is not used when the degraded mode is enabled.
            /// </summary>
            public class ValidateClientType : IOpenIddictServerHandler<ValidateRevocationRequestContext>
            {
                private readonly IOpenIddictApplicationManager _applicationManager;

                public ValidateClientType() => throw new InvalidOperationException(new StringBuilder()
                    .AppendLine("The core services must be registered when enabling the OpenIddict server feature.")
                    .Append("To register the OpenIddict core services, reference the 'OpenIddict.Core' package ")
                    .AppendLine("and call 'services.AddOpenIddict().AddCore()' from 'ConfigureServices'.")
                    .Append("Alternatively, you can disable the built-in database-based server features by enabling ")
                    .Append("the degraded mode with 'services.AddOpenIddict().AddServer().EnableDegradedMode()'.")
                    .ToString());

                public ValidateClientType([NotNull] IOpenIddictApplicationManager applicationManager)
                    => _applicationManager = applicationManager;

                /// <summary>
                /// Gets the default descriptor definition assigned to this handler.
                /// </summary>
                public static OpenIddictServerHandlerDescriptor Descriptor { get; }
                    = OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateRevocationRequestContext>()
                        .AddFilter<RequireClientIdParameter>()
                        .AddFilter<RequireDegradedModeDisabled>()
                        .UseScopedHandler<ValidateClientType>()
                        .SetOrder(ValidateClientId.Descriptor.Order + 1_000)
                        .SetType(OpenIddictServerHandlerType.BuiltIn)
                        .Build();

                /// <summary>
                /// Processes the event.
                /// </summary>
                /// <param name="context">The context associated with the event to process.</param>
                /// <returns>
                /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
                /// </returns>
                public async ValueTask HandleAsync([NotNull] ValidateRevocationRequestContext context)
                {
                    if (context == null)
                    {
                        throw new ArgumentNullException(nameof(context));
                    }

                    var application = await _applicationManager.FindByClientIdAsync(context.ClientId);
                    if (application == null)
                    {
                        throw new InvalidOperationException("The client application details cannot be found in the database.");
                    }

                    if (await _applicationManager.HasClientTypeAsync(application, ClientTypes.Public))
                    {
                        // Reject revocation requests containing a client_secret when the client is a public application.
                        if (!string.IsNullOrEmpty(context.ClientSecret))
                        {
                            context.Logger.LogError("The revocation request was rejected because the public application '{ClientId}' " +
                                                    "was not allowed to send a client secret.", context.ClientId);

                            context.Reject(
                                error: Errors.InvalidClient,
                                description: "The 'client_secret' parameter is not valid for this client application.");

                            return;
                        }

                        return;
                    }

                    // Confidential and hybrid applications MUST authenticate to protect them from impersonation attacks.
                    if (string.IsNullOrEmpty(context.ClientSecret))
                    {
                        context.Logger.LogError("The revocation request was rejected because the confidential or hybrid application " +
                                                "'{ClientId}' didn't specify a client secret.", context.ClientId);

                        context.Reject(
                            error: Errors.InvalidClient,
                            description: "The 'client_secret' parameter required for this client application is missing.");

                        return;
                    }
                }
            }

            /// <summary>
            /// Contains the logic responsible of rejecting revocation requests specifying an invalid client secret.
            /// Note: this handler is not used when the degraded mode is enabled.
            /// </summary>
            public class ValidateClientSecret : IOpenIddictServerHandler<ValidateRevocationRequestContext>
            {
                private readonly IOpenIddictApplicationManager _applicationManager;

                public ValidateClientSecret() => throw new InvalidOperationException(new StringBuilder()
                    .AppendLine("The core services must be registered when enabling the OpenIddict server feature.")
                    .Append("To register the OpenIddict core services, reference the 'OpenIddict.Core' package ")
                    .AppendLine("and call 'services.AddOpenIddict().AddCore()' from 'ConfigureServices'.")
                    .Append("Alternatively, you can disable the built-in database-based server features by enabling ")
                    .Append("the degraded mode with 'services.AddOpenIddict().AddServer().EnableDegradedMode()'.")
                    .ToString());

                public ValidateClientSecret([NotNull] IOpenIddictApplicationManager applicationManager)
                    => _applicationManager = applicationManager;

                /// <summary>
                /// Gets the default descriptor definition assigned to this handler.
                /// </summary>
                public static OpenIddictServerHandlerDescriptor Descriptor { get; }
                    = OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateRevocationRequestContext>()
                        .AddFilter<RequireClientIdParameter>()
                        .AddFilter<RequireDegradedModeDisabled>()
                        .UseScopedHandler<ValidateClientSecret>()
                        .SetOrder(ValidateClientType.Descriptor.Order + 1_000)
                        .SetType(OpenIddictServerHandlerType.BuiltIn)
                        .Build();

                /// <summary>
                /// Processes the event.
                /// </summary>
                /// <param name="context">The context associated with the event to process.</param>
                /// <returns>
                /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
                /// </returns>
                public async ValueTask HandleAsync([NotNull] ValidateRevocationRequestContext context)
                {
                    if (context == null)
                    {
                        throw new ArgumentNullException(nameof(context));
                    }

                    var application = await _applicationManager.FindByClientIdAsync(context.ClientId);
                    if (application == null)
                    {
                        throw new InvalidOperationException("The client application details cannot be found in the database.");
                    }

                    // If the application is not a public client, validate the client secret.
                    if (!await _applicationManager.HasClientTypeAsync(application, ClientTypes.Public) &&
                        !await _applicationManager.ValidateClientSecretAsync(application, context.ClientSecret))
                    {
                        context.Logger.LogError("The revocation request was rejected because the confidential or hybrid application " +
                                                "'{ClientId}' didn't specify valid client credentials.", context.ClientId);

                        context.Reject(
                            error: Errors.InvalidClient,
                            description: "The specified client credentials are invalid.");

                        return;
                    }
                }
            }

            /// <summary>
            /// Contains the logic responsible of rejecting revocation requests made by
            /// applications that haven't been granted the revocation endpoint permission.
            /// Note: this handler is not used when the degraded mode is enabled.
            /// </summary>
            public class ValidateEndpointPermissions : IOpenIddictServerHandler<ValidateRevocationRequestContext>
            {
                private readonly IOpenIddictApplicationManager _applicationManager;

                public ValidateEndpointPermissions() => throw new InvalidOperationException(new StringBuilder()
                    .AppendLine("The core services must be registered when enabling the OpenIddict server feature.")
                    .Append("To register the OpenIddict core services, reference the 'OpenIddict.Core' package ")
                    .AppendLine("and call 'services.AddOpenIddict().AddCore()' from 'ConfigureServices'.")
                    .Append("Alternatively, you can disable the built-in database-based server features by enabling ")
                    .Append("the degraded mode with 'services.AddOpenIddict().AddServer().EnableDegradedMode()'.")
                    .ToString());

                public ValidateEndpointPermissions([NotNull] IOpenIddictApplicationManager applicationManager)
                    => _applicationManager = applicationManager;

                /// <summary>
                /// Gets the default descriptor definition assigned to this handler.
                /// </summary>
                public static OpenIddictServerHandlerDescriptor Descriptor { get; }
                    = OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateRevocationRequestContext>()
                        .AddFilter<RequireClientIdParameter>()
                        .AddFilter<RequireDegradedModeDisabled>()
                        .AddFilter<RequireEndpointPermissionsEnabled>()
                        .UseScopedHandler<ValidateEndpointPermissions>()
                        .SetOrder(ValidateClientSecret.Descriptor.Order + 1_000)
                        .SetType(OpenIddictServerHandlerType.BuiltIn)
                        .Build();

                /// <summary>
                /// Processes the event.
                /// </summary>
                /// <param name="context">The context associated with the event to process.</param>
                /// <returns>
                /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
                /// </returns>
                public async ValueTask HandleAsync([NotNull] ValidateRevocationRequestContext context)
                {
                    if (context == null)
                    {
                        throw new ArgumentNullException(nameof(context));
                    }

                    var application = await _applicationManager.FindByClientIdAsync(context.ClientId);
                    if (application == null)
                    {
                        throw new InvalidOperationException("The client application details cannot be found in the database.");
                    }

                    // Reject the request if the application is not allowed to use the revocation endpoint.
                    if (!await _applicationManager.HasPermissionAsync(application, Permissions.Endpoints.Revocation))
                    {
                        context.Logger.LogError("The revocation request was rejected because the application '{ClientId}' " +
                                                "was not allowed to use the revocation endpoint.", context.ClientId);

                        context.Reject(
                            error: Errors.UnauthorizedClient,
                            description: "This client application is not allowed to use the revocation endpoint.");

                        return;
                    }
                }
            }

            /// <summary>
            /// Contains the logic responsible of rejecting revocation requests that don't specify a valid token.
            /// </summary>
            public class ValidateToken : IOpenIddictServerHandler<ValidateRevocationRequestContext>
            {
                private readonly IOpenIddictServerDispatcher _dispatcher;

                public ValidateToken([NotNull] IOpenIddictServerDispatcher dispatcher)
                    => _dispatcher = dispatcher;

                /// <summary>
                /// Gets the default descriptor definition assigned to this handler.
                /// </summary>
                public static OpenIddictServerHandlerDescriptor Descriptor { get; }
                    = OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateRevocationRequestContext>()
                        .UseScopedHandler<ValidateToken>()
                        .SetOrder(ValidateEndpointPermissions.Descriptor.Order + 1_000)
                        .SetType(OpenIddictServerHandlerType.BuiltIn)
                        .Build();

                /// <summary>
                /// Processes the event.
                /// </summary>
                /// <param name="context">The context associated with the event to process.</param>
                /// <returns>
                /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
                /// </returns>
                public async ValueTask HandleAsync([NotNull] ValidateRevocationRequestContext context)
                {
                    if (context == null)
                    {
                        throw new ArgumentNullException(nameof(context));
                    }

                    var notification = new ProcessAuthenticationContext(context.Transaction);
                    await _dispatcher.DispatchAsync(notification);

                    if (notification.IsRequestHandled)
                    {
                        context.HandleRequest();
                        return;
                    }

                    else if (notification.IsRequestSkipped)
                    {
                        context.SkipRequest();
                        return;
                    }

                    else if (notification.IsRejected)
                    {
                        context.Reject(
                            error: notification.Error ?? Errors.InvalidRequest,
                            description: notification.ErrorDescription,
                            uri: notification.ErrorUri);
                        return;
                    }

                    // Attach the security principal extracted from the token to the validation context.
                    context.Principal = notification.Principal;
                }
            }

            /// <summary>
            /// Contains the logic responsible of rejecting revocation requests that specify an unsupported token.
            /// </summary>
            public class ValidateTokenType : IOpenIddictServerHandler<ValidateRevocationRequestContext>
            {
                /// <summary>
                /// Gets the default descriptor definition assigned to this handler.
                /// </summary>
                public static OpenIddictServerHandlerDescriptor Descriptor { get; }
                    = OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateRevocationRequestContext>()
                        .UseSingletonHandler<ValidateTokenType>()
                        .SetOrder(ValidateToken.Descriptor.Order + 1_000)
                        .SetType(OpenIddictServerHandlerType.BuiltIn)
                        .Build();

                /// <summary>
                /// Processes the event.
                /// </summary>
                /// <param name="context">The context associated with the event to process.</param>
                /// <returns>
                /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
                /// </returns>
                public ValueTask HandleAsync([NotNull] ValidateRevocationRequestContext context)
                {
                    if (context == null)
                    {
                        throw new ArgumentNullException(nameof(context));
                    }

                    if (!context.Principal.HasTokenType(TokenTypeHints.AccessToken) &&
                        !context.Principal.HasTokenType(TokenTypeHints.AuthorizationCode) &&
                        !context.Principal.HasTokenType(TokenTypeHints.RefreshToken))
                    {
                        context.Logger.LogError("The revocation request was rejected because " +
                                                "the received token was of an unsupported type.");

                        context.Reject(
                            error: Errors.UnsupportedTokenType,
                            description: "This token cannot be revoked.");

                        return default;
                    }

                    return default;
                }
            }

            /// <summary>
            /// Contains the logic responsible of rejecting revocation requests that specify a token
            /// that cannot be revoked by the client application sending the revocation requests.
            /// </summary>
            public class ValidateAuthorizedParty : IOpenIddictServerHandler<ValidateRevocationRequestContext>
            {
                /// <summary>
                /// Gets the default descriptor definition assigned to this handler.
                /// </summary>
                public static OpenIddictServerHandlerDescriptor Descriptor { get; }
                    = OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateRevocationRequestContext>()
                        // Note: when client identification is not enforced, this handler cannot validate
                        // the audiences/presenters if the client_id of the calling application is not known.
                        // In this case, the risk is quite limited as claims are never returned by this endpoint.
                        .AddFilter<RequireClientIdParameter>()
                        .UseSingletonHandler<ValidateAuthorizedParty>()
                        .SetOrder(ValidateTokenType.Descriptor.Order + 1_000)
                        .SetType(OpenIddictServerHandlerType.BuiltIn)
                        .Build();

                /// <summary>
                /// Processes the event.
                /// </summary>
                /// <param name="context">The context associated with the event to process.</param>
                /// <returns>
                /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
                /// </returns>
                public ValueTask HandleAsync([NotNull] ValidateRevocationRequestContext context)
                {
                    if (context == null)
                    {
                        throw new ArgumentNullException(nameof(context));
                    }

                    // When the revoked token is an authorization code, the caller must be
                    // listed as a presenter (i.e the party the authorization code was issued to).
                    if (context.Principal.HasTokenType(TokenTypeHints.AuthorizationCode))
                    {
                        if (!context.Principal.HasPresenter())
                        {
                            throw new InvalidOperationException("The presenters list cannot be extracted from the authorization code.");
                        }

                        if (!context.Principal.HasPresenter(context.ClientId))
                        {
                            context.Logger.LogError("The revocation request was rejected because the " +
                                                    "authorization code was issued to a different client.");

                            context.Reject(
                                error: Errors.InvalidToken,
                                description: "The client application is not allowed to revoke the specified token.");

                            return default;
                        }

                        return default;
                    }

                    // When the revoked token is an access token, the caller must be listed either as a presenter
                    // (i.e the party the token was issued to) or as an audience (i.e a resource server/API).
                    // If the access token doesn't contain any explicit presenter/audience, the token is assumed
                    // to be not specific to any resource server/client application and the check is bypassed.
                    if (context.Principal.HasTokenType(TokenTypeHints.AccessToken) &&
                        context.Principal.HasAudience() && !context.Principal.HasAudience(context.ClientId) &&
                        context.Principal.HasPresenter() && !context.Principal.HasPresenter(context.ClientId))
                    {
                        context.Logger.LogError("The revocation request was rejected because the access token " +
                                                "was issued to a different client or for another resource server.");

                        context.Reject(
                            error: Errors.InvalidToken,
                            description: "The client application is not allowed to revoke the specified token.");

                        return default;
                    }

                    // When the revoked token is an identity token, the caller must be listed as an audience
                    // (i.e the client application the identity token was initially issued to).
                    // If the identity token doesn't contain any explicit audience, the token is
                    // assumed to be not specific to any client application and the check is bypassed.
                    if (context.Principal.HasTokenType(TokenTypeHints.IdToken) &&
                        context.Principal.HasAudience() && !context.Principal.HasAudience(context.ClientId))
                    {
                        context.Logger.LogError("The revocation request was rejected because the " +
                                                "identity token was issued to a different client.");

                        context.Reject(
                            error: Errors.InvalidToken,
                            description: "The client application is not allowed to revoke the specified token.");

                        return default;
                    }

                    // When the revoked token is a refresh token, the caller must be
                    // listed as a presenter (i.e the party the token was issued to).
                    // If the refresh token doesn't contain any explicit presenter, the token is
                    // assumed to be not specific to any client application and the check is bypassed.
                    if (context.Principal.HasTokenType(TokenTypeHints.RefreshToken) &&
                        context.Principal.HasPresenter() && !context.Principal.HasPresenter(context.ClientId))
                    {
                        context.Logger.LogError("The revocation request was rejected because the " +
                                                "refresh token was issued to a different client.");

                        context.Reject(
                            error: Errors.InvalidToken,
                            description: "The client application is not allowed to revoke the specified token.");

                        return default;
                    }

                    return default;
                }
            }

            /// <summary>
            /// Contains the logic responsible of attaching the principal
            /// extracted from the revoked token to the event context.
            /// </summary>
            public class AttachPrincipal : IOpenIddictServerHandler<HandleRevocationRequestContext>
            {
                /// <summary>
                /// Gets the default descriptor definition assigned to this handler.
                /// </summary>
                public static OpenIddictServerHandlerDescriptor Descriptor { get; }
                    = OpenIddictServerHandlerDescriptor.CreateBuilder<HandleRevocationRequestContext>()
                        .UseSingletonHandler<AttachPrincipal>()
                        .SetOrder(int.MinValue + 100_000)
                        .SetType(OpenIddictServerHandlerType.BuiltIn)
                        .Build();

                /// <summary>
                /// Processes the event.
                /// </summary>
                /// <param name="context">The context associated with the event to process.</param>
                /// <returns>
                /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
                /// </returns>
                public ValueTask HandleAsync([NotNull] HandleRevocationRequestContext context)
                {
                    if (context == null)
                    {
                        throw new ArgumentNullException(nameof(context));
                    }

                    var notification = context.Transaction.GetProperty<ValidateRevocationRequestContext>(
                        typeof(ValidateRevocationRequestContext).FullName) ??
                        throw new InvalidOperationException("The authentication context cannot be found.");

                    context.Principal ??= notification.Principal;

                    return default;
                }
            }

            /// <summary>
            /// Contains the logic responsible of revoking the token sent by the client application.
            /// Note: this handler is not used when the degraded mode is enabled.
            /// </summary>
            public class RevokeToken : IOpenIddictServerHandler<HandleRevocationRequestContext>
            {
                private readonly IOpenIddictTokenManager _tokenManager;

                public RevokeToken() => throw new InvalidOperationException(new StringBuilder()
                    .AppendLine("The core services must be registered when enabling the OpenIddict server feature.")
                    .Append("To register the OpenIddict core services, reference the 'OpenIddict.Core' package ")
                    .AppendLine("and call 'services.AddOpenIddict().AddCore()' from 'ConfigureServices'.")
                    .Append("Alternatively, you can disable the built-in database-based server features by enabling ")
                    .Append("the degraded mode with 'services.AddOpenIddict().AddServer().EnableDegradedMode()'.")
                    .ToString());

                public RevokeToken([NotNull] IOpenIddictTokenManager tokenManager)
                    => _tokenManager = tokenManager;

                /// <summary>
                /// Gets the default descriptor definition assigned to this handler.
                /// </summary>
                public static OpenIddictServerHandlerDescriptor Descriptor { get; }
                    = OpenIddictServerHandlerDescriptor.CreateBuilder<HandleRevocationRequestContext>()
                        .AddFilter<RequireDegradedModeDisabled>()
                        .UseScopedHandler<RevokeToken>()
                        .SetOrder(AttachPrincipal.Descriptor.Order + 1_000)
                        .SetType(OpenIddictServerHandlerType.BuiltIn)
                        .Build();

                /// <summary>
                /// Processes the event.
                /// </summary>
                /// <param name="context">The context associated with the event to process.</param>
                /// <returns>
                /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
                /// </returns>
                public async ValueTask HandleAsync([NotNull] HandleRevocationRequestContext context)
                {
                    if (context == null)
                    {
                        throw new ArgumentNullException(nameof(context));
                    }

                    // Extract the token identifier from the authentication principal.
                    var identifier = context.Principal.GetTokenId();
                    if (string.IsNullOrEmpty(identifier))
                    {
                        context.Logger.LogError("The revocation request was rejected because the token had no internal identifier.");

                        context.Reject(
                            error: Errors.UnsupportedTokenType,
                            description: "The specified token cannot be revoked.");

                        return;
                    }

                    var token = await _tokenManager.FindByIdAsync(identifier);
                    if (token == null)
                    {
                        context.Logger.LogInformation("The token '{Identifier}' was not revoked because it couldn't be found.", identifier);

                        context.Reject(
                            error: Errors.InvalidToken,
                            description: "The specified token is invalid.");

                        return;
                    }

                    // Try to revoke the token. If an error occurs, return an error.
                    if (!await _tokenManager.TryRevokeAsync(token))
                    {
                        context.Reject(
                            error: Errors.UnsupportedTokenType,
                            description: "The specified token cannot be revoked.");

                        return;
                    }
                }
            }

            /// <summary>
            /// Contains the logic responsible of converting revocation errors to standard empty responses.
            /// </summary>
            public class NormalizeErrorResponse : IOpenIddictServerHandler<ApplyRevocationResponseContext>
            {
                /// <summary>
                /// Gets the default descriptor definition assigned to this handler.
                /// </summary>
                public static OpenIddictServerHandlerDescriptor Descriptor { get; }
                    = OpenIddictServerHandlerDescriptor.CreateBuilder<ApplyRevocationResponseContext>()
                        .UseSingletonHandler<NormalizeErrorResponse>()
                        .SetOrder(int.MinValue + 100_000)
                        .SetType(OpenIddictServerHandlerType.BuiltIn)
                        .Build();

                /// <summary>
                /// Processes the event.
                /// </summary>
                /// <param name="context">The context associated with the event to process.</param>
                /// <returns>
                /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
                /// </returns>
                public ValueTask HandleAsync([NotNull] ApplyRevocationResponseContext context)
                {
                    if (context == null)
                    {
                        throw new ArgumentNullException(nameof(context));
                    }

                    if (string.IsNullOrEmpty(context.Error))
                    {
                        return default;
                    }

                    // If the error indicates an invalid token, remove the error details, as required by the revocation
                    // specification. Visit https://tools.ietf.org/html/rfc7009#section-2.2 for more information.
                    // While this prevent the resource server from determining the root cause of the revocation failure,
                    // this is required to keep OpenIddict fully standard and compatible with all revocation clients.

                    if (string.Equals(context.Error, Errors.InvalidToken, StringComparison.Ordinal))
                    {
                        context.Response.Error = null;
                        context.Response.ErrorDescription = null;
                        context.Response.ErrorUri = null;
                    }

                    return default;
                }
            }
        }
    }
}


text:
\hypertarget{_i_object_8h}{\section{A\-:/\-I\-T/\-Git\-Hub/\-I\-C\-T312/source/ogregraphics/\-I\-Object.h File Reference}
\label{_i_object_8h}\index{A\-:/\-I\-T/\-Git\-Hub/\-I\-C\-T312/source/ogregraphics/\-I\-Object.\-h@{A\-:/\-I\-T/\-Git\-Hub/\-I\-C\-T312/source/ogregraphics/\-I\-Object.\-h}}
}

Declares the I\-Object interface.

{\ttfamily \#include \char`\"{}Collision\-Object.\-h\char`\"{}}\\*
\subsection*{Classes}
\begin{DoxyCompactItemize}
\item
class \hyperlink{class_objects_1_1_i_object}{Objects\-::\-I\-Object}
\begin{DoxyCompactList}\small\item\em Object. \end{DoxyCompactList}\end{DoxyCompactItemize}

\subsection{Detailed Description}
Declares the I\-Object interface.

redpajama_set_name: RedPajamaGithub


text: {% include menu-search.html %}


text:
package com.gs.collections.api.multimap;

import java.util.Collection;

import com.gs.collections.api.RichIterable;
import com.gs.collections.api.bag.Bag;
import com.gs.collections.api.block.function.Function0;
import com.gs.collections.api.block.procedure.Procedure;
import com.gs.collections.api.block.procedure.Procedure2;
import com.gs.collections.api.map.MutableMap;
import com.gs.collections.api.tuple.Pair;

/**
 * This collection is a type of {@code Map} that can associate multiple values for keys.
 *

 *
Unlike {@code Map} however, this interface is read-only so the results of access methods such as {@link
 * #get(Object)} return a view onto the values associated with that key. The {@link MutableMultimap} subinterface
 * provides methods to mutate the collection.
 *

 *
The advantages to using this container over a {@code Map<K, Collection<V>>} is that all of the handling of the
 * value collection can be done automatically.  It also allows implementations to further specialize in how duplicate
 * values will be handled.  Value collections with list semantics would allow duplicate values for a key, while those
 * implementing set semantics would not.
 *

 *
Internal iteration methods for keys and values (singly - {@link #forEachKey(Procedure)}, {@link
 * #forEachValue(Procedure)}, and together - {@link #forEachKeyValue(Procedure2)}) are provided to allow flexible
 * browsing of the collection's contents.  Similarly, views also are provided for keys ({@link #keysView()}), values
 * ({@link #valuesView()}) and the combination thereof ({@link #keyValuePairsView()}, {@link
 * #keyMultiValuePairsView()}).
 *

 *
 * @param <K> the type of keys used
 * @param <V> the type of mapped values
 * @since 1.0
 */
public interface Multimap<K, V>
{
    /**
     * Creates a new instance of the same implementation type, using the default capacity and growth parameters.
     */
    Multimap<K, V> newEmpty();

    /**
     * Returns {@code true} if there are no entries.
     */
    boolean isEmpty();

    /**
     * Returns {@code true} if there is at least one entry.
     */
    boolean notEmpty();

    /**
     * Calls the procedure with each value.
     *

     * Given a Multimap with the contents:
     *

     * { "key1" : ["val1", "val2", "val2"], "key2" : ["val3"] }
     *

     * The given procedure would be invoked with the parameters:
     *

     * [ "val1", "val2", "val2", "val3" ]
     */
    void forEachValue(Procedure<? super V> procedure);

    /**
     * Calls the procedure with each key.
     *

     * Given a Multimap with the contents:
     *

     * { "key1" : ["val1", "val2", "val2"], "key2" : ["val3"] }
     *

     * The given procedure would be invoked with the parameters:
     *

     * [ "key1", "key2" ]
     */
    void forEachKey(Procedure<? super K> procedure);

    /**
     * Calls the procedure with each key-value pair.
     *

     * Given a Multimap with the contents:
     *

     * { "key1" : ["val1", "val2", "val2"], "key2" : ["val3"] }
     *

     * The given procedure would be invoked with the parameters:
     *

     * [ ["key1", "val1"], ["key1", "val2"], ["key1", "val2"], ["key2", "val3"] ]
     */
    void forEachKeyValue(Procedure2<K, V> procedure);

    /**
     * Returns the number of key-value entry pairs.
     *

     * This method is implemented with O(1) (constant-time) performance.
     */
    int size();

    /**
     * Returns the number of distinct keys.
     */
    int sizeDistinct();

    /**
     * Returns {@code true} if any values are mapped to the specified key.
     *
     * @param key the key to search for
     */
    boolean containsKey(Object key);

    /**
     * Returns {@code true} if any key is mapped to the specified value.
     *
     * @param value the value to search for
     */
    boolean containsValue(Object value);

    /**
     * Returns {@code true} if the specified key-value pair is mapped.
     *
     * @param key   the key to search for
     * @param value the value to search for
     */
    boolean containsKeyAndValue(Object key, Object value);

    /**
     * Returns a view of all values associated with the given key.
     *

     * If the given key does not exist, an empty {@link RichIterable} is returned.
     *
     * @param key the key to search for
     */
    RichIterable<V> get(K key);

    /**
     * Returns a lazy view of the unique keys.
     */
    RichIterable<K> keysView();

    /**
     * Returns a {@link Bag} of keys with the count corresponding to the number of mapped values.
     */
    Bag<K> keyBag();

    /**
     * Returns an unmodifiable view of all of the values mapped to each key.
     */
    RichIterable<RichIterable<V>> multiValuesView();

    /**
     * Returns a lazy flattened view of all the values.
     */
    RichIterable<V> valuesView();

    /**
     * Returns a lazy view of the pair of a key and and a lazy view of the values mapped to that key.
     */
    RichIterable<Pair<K, RichIterable<V>>> keyMultiValuePairsView();

    /**
     * Returns a lazy view of all of the key/value pairs.
     */
    RichIterable<Pair<K, V>> keyValuePairsView();

    /**
     * Returns a new {@link MutableMap} of keys from this Multimap to the mapped values as a {@link RichIterable}.
     */
    MutableMap<K, RichIterable<V>> toMap();

    /**
     * Returns a new {@link MutableMap} of keys from this Multimap to the mapped values as a {@link RichIterable}.
     *
     * @param collectionFactory used to create the collections that hold the values and affects the return type
     */
    <R extends Collection<V>> MutableMap<K, R> toMap(Function0<R> collectionFactory);

    /**
     * Compares the specified object with this Multimap for equality.
     *

     * Two Multimaps are equal when their map views (as returned by {@link #toMap}) are also equal.
     *

     *
In general, two Multimaps with identical key-value mappings may or may not be equal, depending on the type of
     * the collections holding the values. If the backing collections are Sets, then two instances with the same
     * key-value mappings are equal, but if the backing collections are Lists, equality depends on the ordering of the
     * values for each key.
     *

     * Any two empty Multimaps are equal, because they both have empty {@link #toMap} views.
     */
    @Override
    boolean equals(Object obj);

    /**
     * Returns the hash code for this Multimap.
     *

     *
The hash code of a Multimap is defined as the hash code of the map view, as returned by {@link #toMap}.
     */
    @Override
    int hashCode();

    /**
     * Returns a mutable copy of this Multimap.
     */
    MutableMultimap<K, V> toMutable();

    /**
     * Returns an immutable copy of this Multimap if it is not already immutable. If the Multimap is immutable,
     * it will return itself.
     *

     * The returned Multimap will be {@code Serializable} if this Multimap is {@code Serializable}.
     */
    ImmutableMultimap<K, V> toImmutable();
}


text:
#pragma once
#if !defined(__MITSUBA_CORE_COBJECT_H_)
#define __MITSUBA_CORE_COBJECT_H_

#include <mitsuba/mitsuba.h>
#include <mitsuba/core/serialization.h>
#include <mitsuba/core/properties.h>

MTS_NAMESPACE_BEGIN

/** \brief Generic serializable object, which supports construction
* from a Properties instance.
 *
 * All plugins in Mitsuba derive from ConfigurableObject. This mechanism
 * lets them accept parameters specified in an external XML file. Additionally,
 * they can have child objects, which correspond to nested instantiation
 * requests in the XML file.
 *
 * \ingroup libcore
 * \ingroup libpython
 */
class MTS_EXPORT_CORE ConfigurableObject : public SerializableObject {
public:
	/**
	 * \brief Notify the \ref ConfigurableObject instance about
	 * its parent object
	 *
	 * The default implementation does nothing.
	 */
	virtual void setParent(ConfigurableObject *parent);

	/// Add a child (default implementation throws an error)
	virtual void addChild(const std::string &name, ConfigurableObject *child);

	/// Add an unnamed child
	inline void addChild(ConfigurableObject *child) { addChild("", child); }

	/** \brief Configure the object (called \a once after construction
	   and addition of all child \ref ConfigurableObject instances)) */
	virtual void configure();

	/// Serialize this object to a binary data stream
	virtual void serialize(Stream *stream, InstanceManager *manager) const;

	/// Return the identifier associated with this instance (or "unnamed")
	inline const std::string &getID() const { return m_properties.getID(); }

	/// Set the identifier associated with this instance
	inline void setID(const std::string &name) { m_properties.setID(name); }

	/**
	 * \brief Return the properties object that was originally used to
	 * create this instance
	 *
	 * This feature mainly of use for editors and other graphical
	 * user interfaces, which present the properties of an object
	 * in some form.
	 */
	inline const Properties &getProperties() const { return m_properties; }

	MTS_DECLARE_CLASS()
protected:
	/// Virtual destructor
	virtual ~ConfigurableObject() { }

	/// Construct a configurable object
	inline ConfigurableObject(const Properties &props)
		: SerializableObject(), m_properties(props) { }

	/// Unserialize a configurable object
	ConfigurableObject(Stream *stream, InstanceManager *manager);
protected:
	Properties m_properties;
};

/** \brief This macro creates the binary interface, which Mitsuba
 * requires to load a plugin.
 *
 * \ingroup libcore
 */
#define MTS_EXPORT_PLUGIN(name, descr) \
	extern "C" { \
		void MTS_EXPORT *CreateInstance(const Properties &props) { \
			return new name(props); \
		} \
		const char MTS_EXPORT *GetDescription() { \
			return descr; \
		} \
	}

MTS_NAMESPACE_END

#endif /* __MITSUBA_CORE_COBJECT_H_ */


text:
package org.zmpp.glk.io;

import java.util.logging.*;
import java.util.List;
import java.util.ArrayList;

public final class GlkIOSystem {

    private static Logger logger = Logger.getLogger("glk");
    private int _nextId = 1;
    private List<GlkStream> _streams = new ArrayList<GlkStream>();
    private GlkStream _currentStream = NilStream.getInstance();

    public GlkStream streamWithId(int id) {
        for (GlkStream stream: _streams) {
            if (stream.id() == id) return stream;
        }
        return null;
    }

    public int registerStream(GlkStream stream) {
        stream.setId(_nextId);
        _streams.add(stream);
        _nextId += 1;
        return stream.id();
    }

    public GlkStream iterate(int id) {
        if (_streams.isEmpty()) return null;
        else if (id == 0) return _streams.get(0);
        else {
            int i = 0;
            for (i = 0; i < _streams.size(); i++) {
                if (_streams.get(i).id() == id) break;
            }
            if (i >= _streams.size() - 1) return null;
            else return _streams.get(i + 1);
        }
    }

    public GlkStreamCloseStruct closeStream(int id) {
        GlkStream stream = streamWithId(id);
        _streams.remove(stream);
        stream.close();
        if (stream == _currentStream) _currentStream = NilStream.getInstance();
        return new GlkStreamCloseStruct(stream.writeCount(), stream.readCount());
    }

    public int getPosition(int id) { return streamWithId(id).position(); }
    public void setPosition(int id, int pos, int seekmode) {
        streamWithId(id).seek(pos, seekmode);
    }

    public void putChar(int id, char c) { streamWithId(id).putChar(c); }
    public void putCharUni(int id, int c) { streamWithId(id).putCharUni(c); }

    // control current stream
    public GlkStream currentStream() { return _currentStream; }
    public void setCurrentStream(GlkStream s) {
        _currentStream = (s == null) ? NilStream.getInstance() : s;
    }

    public int currentStreamId() { return _currentStream.id(); }
    public void setCurrentStreamId(int id) { _currentStream = streamWithId(id); }

    public int getRock(int streamId) { return streamWithId(streamId).rock(); }

    public void putChar(char c) { _currentStream.putChar(c); }
    public void putCharUni(int c) { _currentStream.putCharUni(c); }

    // For convenient output (debugging etc.)
    public void putJavaString(String str) {
        for (int i = 0; i < str.length(); i++) {
            putCharUni(str.charAt(i));
        }
    }

    public void setHyperlink(int linkval) { _currentStream.setHyperlink(linkval); }
    public void setHyperlinkStream(int streamId, int linkval) {
        streamWithId(streamId).setHyperlink(linkval);
    }

    public int currentStyle() { return _currentStream.style(); }
    public void setCurrentStyle(int value) { _currentStream.setStyle(value); }

    public void setStyle(int streamId, int value) {
        streamWithId(streamId).setStyle(value);
    }

    // reading
    public int getCharStream(int streamId) { return streamWithId(streamId).getChar(); }
    public int getCharStreamUni(int streamId) { return streamWithId(streamId).getCharUni(); }
}


text:
namespace SharpRhythms.Enums
{
    public enum StepChartType
    {
        /// <summary>
        /// Singleplayer one pad
        /// </summary>
        Single,
        /// <summary>
        /// Singleplayer two pads
        /// </summary>
        Double,
        /// <summary>
        /// Multiplayer versus
        /// </summary>
        Battle,
        /// <summary>
        /// Singleplayer one pad with additional arrow directions
        /// </summary>
        Solo
    }
}


text:
require 'test_helper'

class WelcomeControllerTest < ActionController::TestCase
  test "should get index" do
    get :index
    assert_response :success
    assert_template :index
  end
end


text:
'use strict';

var tape = require('../lib/thaliTape');
var testUtils = require('../lib/testUtils.js');

var extend = require('js-extend').extend;
var crypto = require('crypto');
var Promise = require('bluebird');
var PouchDB = require('pouchdb');
var express = require('express');
var expressPouchDB = require('express-pouchdb');

var proxyquire = require('proxyquire').noCallThru();

var Salti = require('salti');
var thaliConfig = require('thali/NextGeneration/thaliConfig');
var ThaliPeerPoolDefault =
  require('thali/NextGeneration/thaliPeerPool/thaliPeerPoolDefault');

var ThaliMobile = require('thali/NextGeneration/thaliMobile');
var ThaliSendNotificationBasedOnReplication =
  require('thali/NextGeneration/replication/thaliSendNotificationBasedOnReplication');
var ThaliPullReplicationFromNotification =
  require('thali/NextGeneration/replication/thaliPullReplicationFromNotification');
var ThaliNotificationServer =
  require('thali/NextGeneration/notification/thaliNotificationServer');

// Public key for local device should be passed
// to the tape 'setup' as 'tape.data'.
var ecdhForLocalDevice = crypto.createECDH(thaliConfig.BEACON_CURVE);
var publicKeyForLocalDevice = ecdhForLocalDevice.generateKeys();

var test = tape({
  setup: function (t) {
    t.data = publicKeyForLocalDevice.toJSON();
    t.end();
  },
  teardown: function (t) {
    t.end();
  }
});

function Mocks(t, sandbox) {
  // All objects should be cloned in order to prevent
  // 'already wrapped' error by 'sinon.spy'.

  this.t = t;

  this.express          = sandbox.spy(express);
  this.expressPouchDB   = sandbox.spy(expressPouchDB);
  this.LevelDownPouchDB = sandbox.spy(testUtils.getLevelDownPouchDb());

  this.ThaliMobile = extend({}, ThaliMobile);

  this.MobileStart = sandbox.spy(this.ThaliMobile, 'start');
  this.MobileStop  = sandbox.spy(this.ThaliMobile, 'stop');

  this.MobileStartLA = sandbox.spy(
    this.ThaliMobile, 'startListeningForAdvertisements'
  );
  this.MobileStartUAA = sandbox.spy(
    this.ThaliMobile, 'startUpdateAdvertisingAndListening'
  );

  this.Notification = sandbox.spy(
    ThaliSendNotificationBasedOnReplication
  );
  this.Notification.prototype = extend(
    {},
    ThaliSendNotificationBasedOnReplication.prototype
  );
  this.NotificationStart = sandbox.spy(
    this.Notification.prototype, 'start'
  );
  this.NotificationStop = sandbox.spy(
    this.Notification.prototype, 'stop'
  );

  this.Replication = sandbox.spy(
    ThaliPullReplicationFromNotification
  );
  this.Replication.prototype = extend(
    {},
    ThaliPullReplicationFromNotification.prototype
  );
  this.ReplicationStart = sandbox.spy(
    this.Replication.prototype, 'start'
  );
  this.ReplicationStop = sandbox.spy(
    this.Replication.prototype, 'stop'
  );

  this.Salti = sandbox.spy(Salti);
  this.ThaliManager =
    proxyquire('thali/NextGeneration/thaliManager', {
      './replication/thaliSendNotificationBasedOnReplication':
        this.Notification,
      './replication/thaliPullReplicationFromNotification':
        this.Replication,
      './thaliMobile': this.ThaliMobile,
      'express': this.express,
      'salti': this.Salti
    });
}

Mocks.prototype.resetStartStop = function() {
  this.MobileStart.reset();
  this.MobileStop.reset();

  this.MobileStartLA.reset();

  this.MobileStartUAA.reset();

  this.NotificationStart.reset();
  this.NotificationStop.reset();

  this.ReplicationStart.reset();
  this.ReplicationStop.reset();
};

Mocks.prototype.checkInit = function(dbName, ecdh, peerPool) {
  this.checkExpressPouchDB();
  this.checkPouchDB(dbName);
  this.checkNotification(ecdh);
  this.checkReplication(dbName, peerPool, ecdh);
  this.checkSalti(dbName);
};
Mocks.prototype.checkStart = function(partnerKeys, networkType) {
  this.checkMobileStart(networkType);
  this.checkMobileStartLA();
  this.checkMobileStartUAA();
  this.checkNotificationStart(partnerKeys);
  this.checkReplicationStart(partnerKeys);
};
Mocks.prototype.checkStop = function() {
  this.checkMobileStop();
  this.checkNotificationStop();
  this.checkReplicationStop();
};

Mocks.prototype.checkExpressPouchDB = function() {
  var self = this;
  testUtils.checkArgs(
    this.t, this.expressPouchDB, 'expressPouchDB',
    [
      {
        description: 'PouchDB',
        compare: function (arg) {
          return typeof arg === 'function' &&
            arg === self.LevelDownPouchDB;
        }
      },
      {
        description: 'expressPouchDB options',
        compare: function (arg) {
          return typeof arg === 'object' &&
            arg.mode === 'minimumForPouchDB';
        }
      }
    ]
  );
};

Mocks.prototype.checkPouchDB = function(dbName) {
  testUtils.checkArgs(
    this.t, this.LevelDownPouchDB, 'PouchDB',
    [{
      description: 'dbName',
      compare: function (arg) {
        return typeof arg === 'string' &&
          arg === dbName;
      }
    }]
  );
};

Mocks.prototype.checkReplication = function(dbName, peerPool, ecdh) {
  var self = this;
  testUtils.checkArgs(
    this.t, this.Replication, 'ThaliPullReplicationFromNotification',
    [
      {
        description: 'PouchDB',
        compare: function (arg) {
          return typeof arg === 'function' &&
            arg === self.LevelDownPouchDB;
        }
      },
      {
        description: 'dbName',
        compare: function (arg) {
          return typeof arg === 'string' &&
            arg === dbName;
        }
      },
      {
        description: 'ThaliPeerPoolInterface instance',
        compare: function (arg) {
          return typeof arg === 'object' &&
            arg instanceof ThaliPeerPoolDefault &&
            arg === peerPool;
        }
      },
      {
        description: 'ecdhForLocalDevice',
        compare: function (arg) {
          return typeof arg === 'object' &&
            arg === ecdh;
        }
      }
    ]
  );
};
Mocks.prototype.checkReplicationStart = function(remoteKeys) {
  testUtils.checkArgs(
    this.t, this.ReplicationStart,
    'ThaliPullReplicationFromNotification.prototype.start',
    [{
      description: 'remoteKeys',
      compare: function (arg) {
        return Array.isArray(arg) &&
          arg === remoteKeys;
      }
    }]
  );
};
Mocks.prototype.checkReplicationStop = function() {
  testUtils.checkArgs(
    this.t, this.ReplicationStop,
    'ThaliPullReplicationFromNotification.prototype.stop',
    []
  );
};

Mocks.prototype.checkNotification = function(ecdh) {
  var self = this;
  testUtils.checkArgs(
    this.t, this.Notification, 'ThaliSendNotificationBasedOnReplication',
    [
      {
        description: 'express.Router instance',
        compare: function (arg) {
          return typeof arg === 'function' &&
            // This is not possible to check instanceof express.Router.
            typeof arg.__proto__ === 'function' &&
            arg.__proto__ === self.express.Router;
        }
      },
      {
        description: 'ecdhForLocalDevice',
        compare: function (arg) {
          return typeof arg === 'object' &&
            arg === ecdh;
        }
      },
      {
        description: 'thaliConfig.BEACON_MILLISECONDS_TO_EXPIRE',
        compare: function (arg) {
          return typeof arg === 'number' &&
            arg === thaliConfig.BEACON_MILLISECONDS_TO_EXPIRE;
        }
      },
      {
        description: 'PouchDB instance',
        compare: function (arg) {
          return typeof arg === 'object' &&
            arg instanceof PouchDB;
        }
      }
    ]
  );
};
Mocks.prototype.checkNotificationStart = function(remoteKeys) {
  testUtils.checkArgs(
    this.t, this.NotificationStart,
    'ThaliSendNotificationBasedOnReplication.prototype.start',
    [{
      description: 'remoteKeys',
      compare: function (arg) {
        return Array.isArray(arg) &&
          arg === remoteKeys;
      }
    }]
  );
};
Mocks.prototype.checkNotificationStop = function() {
  testUtils.checkArgs(
    this.t, this.NotificationStop,
    'ThaliSendNotificationBasedOnReplication.prototype.stop',
    []
  );
};

Mocks.prototype.checkMobileStart = function(networkType) {
  var self = this;
  testUtils.checkArgs(
    this.t, this.MobileStart, 'ThaliMobile.start',
    [
      {
        description: 'express.Router instance',
        compare: function (arg) {
          return typeof arg === 'function' &&
            // This is not possible to check instanceof express.Router.
            typeof arg.__proto__ === 'function' &&
            arg.__proto__ === self.express.Router;
        }
      },
      {
        description: 'getPskIdToSecret',
        compare: function (arg) {
          return typeof arg === 'function' &&
            arg.toString() ===
            ThaliNotificationServer.prototype.getPskIdToSecret().toString();
        }
      },
      {
        description: 'networkType',
        compare: function (arg) {
          return arg === networkType;
        }
      }
    ]
  );
};
Mocks.prototype.checkMobileStartLA = function() {
  testUtils.checkArgs(
    this.t, this.MobileStartLA,
    'ThaliMobile.startListeningForAdvertisements',
    []
  );
};
Mocks.prototype.checkMobileStartUAA = function() {
  testUtils.checkArgs(
    this.t, this.MobileStartUAA,
    'ThaliMobile.startUpdateAdvertisingAndListening',
    []
  );
};

Mocks.prototype.checkMobileStop = function() {
  testUtils.checkArgs(
    this.t, this.MobileStop, 'ThaliMobile.stop', []
  );
};

Mocks.prototype.checkSalti = function(dbName) {
  var self = this;
  testUtils.checkArgs(
    this.t, this.Salti, 'Salti',
    [
      {
        description: 'dbName',
        compare: function (arg) {
          return typeof arg === 'string' &&
            arg === dbName;
        }
      },
      {
        description: 'acl',
        compare: function (arg) {
          return typeof arg === 'object' &&
            arg === self.ThaliManager._acl;
        }
      },
      {
        description: 'thaliIdCallback',
        compare: function (arg) {
          return typeof arg === 'function';
        }
      },
      {
        description: 'options',
        compare: function (arg) {
          return typeof arg === 'object' &&
            arg.dbPrefix === thaliConfig.BASE_DB_PATH;
        }
      }
    ]
  );
};

test('test thali manager spies', tape.sinonTest(function (t) {
  // This function will return all participant's public keys
  // except local 'publicKeyForLocalDevice' one.
  var partnerKeys;
  if (t.coordinated) {
    partnerKeys = testUtils.turnParticipantsIntoBufferArray(
      t, publicKeyForLocalDevice
    );
  } else {
    partnerKeys = [];
  }

  var mocks = new Mocks(t, this);

  // Creating thali manager with mocks.
  var dbName = testUtils.getRandomPouchDBName();
  var peerPool = new ThaliPeerPoolDefault();
  var thaliManager = new mocks.ThaliManager(
    mocks.expressPouchDB,
    mocks.LevelDownPouchDB,
    dbName,
    ecdhForLocalDevice,
    peerPool,
    global.NETWORK_TYPE
  );
  mocks.checkInit(dbName, ecdhForLocalDevice, peerPool);

  thaliManager.start(partnerKeys)
  .then(function () {
    mocks.checkStart(partnerKeys, global.NETWORK_TYPE);
  })
  .then(function () {
    return thaliManager.stop();
  })
  .then(function () {
    mocks.checkStop();
    t.end();
  });
}));

test('test thali manager multiple starts and stops', tape.sinonTest(function (t) {
  // This function will return all participant's public keys
  // except local 'publicKeyForLocalDevice' one.
  var partnerKeys;
  if (t.coordinated) {
    partnerKeys = testUtils.turnParticipantsIntoBufferArray(
      t, publicKeyForLocalDevice
    );
  } else {
    partnerKeys = [];
  }

  var mocks = new Mocks(t, this);

  // Creating thali manager with mocks.
  var dbName = testUtils.getRandomPouchDBName();
  var peerPool = new ThaliPeerPoolDefault();
  var thaliManager = new mocks.ThaliManager(
    mocks.expressPouchDB,
    mocks.LevelDownPouchDB,
    dbName,
    ecdhForLocalDevice,
    peerPool,
    global.NETWORK_TYPE
  );
  mocks.checkInit(dbName, ecdhForLocalDevice, peerPool);

  // Multiple parallel starts.
  Promise.all([
    thaliManager.start(partnerKeys),
    thaliManager.start(partnerKeys),
    thaliManager.start(partnerKeys)
  ])
  // Multiple serial starts.
  .then(function () {
    return thaliManager.start(partnerKeys);
  })
  .then(function () {
    return thaliManager.start(partnerKeys);
  })
  .then(function () {
    mocks.checkStart(partnerKeys, global.NETWORK_TYPE);
  })

  // Multiple parallel stops.
  .then(function () {
    return Promise.all([
      thaliManager.stop(),
      thaliManager.stop(),
      thaliManager.stop()
    ]);
  })
  // Multiple serial stops.
  .then(function () {
    return thaliManager.stop();
  })
  .then(function () {
    return thaliManager.stop();
  })
  .then(function () {
    mocks.checkStop();
  })

  // Multiple parallel starts and stops.
  .then(function () {
    return Promise.all([
      thaliManager.start(partnerKeys),
      thaliManager.stop(),
      thaliManager.start(partnerKeys),
      thaliManager.stop(),
      thaliManager.start(partnerKeys),
      thaliManager.stop()
    ]);
  })
  .then(function () {
    return Promise.all([
      thaliManager.start(partnerKeys),
      thaliManager.start(partnerKeys),
      thaliManager.start(partnerKeys),
      thaliManager.stop(),
      thaliManager.stop(),
      thaliManager.stop()
    ]);
  })

  .then(function () {
    mocks.resetStartStop();
    return thaliManager.start(partnerKeys);
  })
  .then(function () {
    mocks.checkStart(partnerKeys, global.NETWORK_TYPE);
  })
  .then(function () {
    return thaliManager.stop();
  })
  .then(function () {
    t.end();
  });
}));


text:
/*
 * Created on 03/03/2014
 *
 */
package net.rlviana.pricegrabber.domain.entity.core;

import net.rlviana.pricegrabber.domain.entity.AbstractEntityTest;

/**
 * @author ramon
 */
public class ItemTypeTest extends AbstractEntityTest<ItemType> {

  /**
   * @return
   * @see net.rlviana.pricegrabber.domain.entity.AbstractEntityTest#getEntityOK()
   */
  @Override
  protected ItemType getEntityOK() {
    return getTestItemType();
  }

  /**
   * @return
   * @see net.rlviana.pricegrabber.domain.entity.AbstractEntityTest#getEntityKO()
   */
  @Override
  protected ItemType getEntityKO() {
    ItemType itemType = new ItemType();
    return itemType;
  }

  /**
   * @return
   * @see net.rlviana.pricegrabber.domain.entity.AbstractEntityTest#getDomainEntityType()
   */
  @Override
  protected Class<ItemType> getDomainEntityType() {
    return ItemType.class;
  }

}


text:
layout: default
title: "List of Stories entries"
teaser: "These are all the stories entries."
breadcrumb: true
sidebar: right
header:
    title: All Stories Entries
    pattern: pattern_jquery-dark-grey-tile.png
permalink: "blog/archive_stories/"
---

{{ page.title }}

		{% if page.teaser %}
{{ page.teaser }}
{% endif %}

			{% assign counter = 1 %}
			{% for post in site.tags.'Stories' limit:1000 %}

			 {% if post.subheadline %}{{ post.subheadline }} › {% endif %}{{ post.title }}

					{% if post.meta_description %}{{ post.meta_description | strip_html | escape }}{% elsif post.teaser %}{{ post.teaser | strip_html | escape }}{% endif %}
					{{ site.data.language.read_more }}

			{% assign counter=counter | plus:1 %}
			{% endfor %}

		{% include sidebar %}


text:
using ElmahLogAnalyzer.Core.Common;

namespace ElmahLogAnalyzer.Core.Domain
{
    using System;

    public class ReportQuery
	{
		public ReportQuery(string application, ReportTypes reportType, DateInterval interval, int numberOfResults)
		{
			Application = application;
			ReportType = reportType;
			Interval = interval;
			NumberOfResults = numberOfResults;
		}

    	public string Application { get; private set; }

		public ReportTypes ReportType { get; private set; }

		public DateInterval Interval { get; private set; }

    	public int NumberOfResults { get; set; }

        public override string ToString()
        {
            return ToString(null);
        }

        public string ToString(IFormatProvider provider)
		{
			return string.Format(provider, "{0} from {1:d} to {2:d}", ReportType.GetDescription(), Interval.StartDate, Interval.EndDate);
		}
	}
}


text:
package com.hwangfantasy.interceptor;

import com.hwangfantasy.config.Constant;
import com.hwangfantasy.enums.RoleEnum;
import com.hwangfantasy.model.SessionUser;
import com.hwangfantasy.util.CookieHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author hwangfantasy
 * @创建时间: 2017/3/2 17:40

 * @方法描述: TODO ADD FUNCTION.

 */
public class AccessInterceptor implements HandlerInterceptor {
    private String[] ignoreUrls = new String[]{"/sample","/index.html"};

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //获取url地址
        String reqUrl = httpServletRequest.getRequestURI().replace(httpServletRequest.getContextPath(), "");
        if (isIgnore(reqUrl)) {
            return true;
        } else {
            HttpSession session = httpServletRequest.getSession();
            if (session == null || session.getAttribute(Constant.SESSION_USER_KEY) == null ||
                    "".equals(session.getAttribute(Constant.SESSION_USER_KEY).toString())) {
                CookieHelper.storeCookie(Constant.LOGIN_COOKIE_KEY, null, httpServletResponse);
                httpServletResponse.sendRedirect(httpServletRequest.getServletContext().getContextPath() + "/login");
                httpServletResponse.flushBuffer();
                return false;
            } else if (!isAccess(httpServletRequest, reqUrl)) {
                httpServletRequest.setCharacterEncoding("UTF-8");
                httpServletResponse.setCharacterEncoding("UTF-8");
                httpServletResponse.setContentType("text/html; charset=UTF-8");
                PrintWriter out = httpServletResponse.getWriter();
                out.write("no access");
                out.close();
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    /**
     * -----------------------------------

     *
     * @作者: hwangfantasy
     * @创建日期: 2017/3/2 17:52

     * -----------------------------------

     * @方法描述: 忽略拦截
     * -----------------------------------

     */
    private boolean isIgnore(String url) {
        for (String s : ignoreUrls) {
            if (url.startsWith(s))
                return true;
        }
        return false;
    }

    /**
     * -----------------------------------

     *
     * @作者: hwangfantasy
     * @创建日期: 2017/3/2 17:52

     * -----------------------------------

     * @方法描述: 权限判断
     * -----------------------------------

     */
    private boolean isAccess(HttpServletRequest request, String reqUrl) {
        SessionUser sessionUser = (SessionUser) request.getSession().getAttribute(Constant.SESSION_USER_KEY);
        if (sessionUser == null)
            return false;
        if (RoleEnum.ROLE_ADMIN.getRole().equals(sessionUser.getRoleName()))//管理员后门
            return true;
        if (RoleEnum.ROLE_DEVLOPER.getRole().equals(sessionUser.getRoleName()))//开发者后门
            return true;
        List<String> permissionUrls = sessionUser.getUrls();
        if (permissionUrls.size() > 0) {
            for (String url : permissionUrls) {
                if (StringUtils.isNotBlank(url.trim()) && reqUrl.indexOf(url.trim()) >= 0 || reqUrl.equals("/index")) {
                    return true;
                }
            }
        }
        return false;
    }
}


text:
import express     from 'express'
import favicon     from 'serve-favicon'
import logger      from 'morgan'
import bodyParser  from 'body-parser'
import compression from 'compression'
import config      from '../../config/server.config'
import db          from './helpers/database' // Even if we don't use it yet, we start db as soon as possible

const app = express()

app.disable('x-powered-by') // Disable useless headers
app.use(compression())

app.use(favicon(config.http.favicon))
app.use('/robots.txt', (req,res) => res.send(config.http.robots))

app.use(logger('dev'))

app.use(bodyParser.json({ limit: '2mb' }))
app.use(bodyParser.urlencoded({ limit: '2mb', extended: true }))

// Serve static files
if (config.http.static.length !== 0) {
    config.http.static.map(route => {
        console.log('[Static] %s -', route.url, route.path)
        app.use(route.url, express.static(route.path))
    })
}

app.use('/*', require('./render.js'))
app.listen(config.http.port)
console.log("Launched ! Running on localhost:"+config.http.port)


text:
autoload promptinit
 fpath=(~/.dotfiles/zsh/prezto-themes ~/.dotfiles/.zsh.prompts $fpath)
promptinit


text:
* adding transpiler option to runEval to transform code after capturing rewrites, e.g. via babel

## 0.5.0

* improved dist build, removing unnecessary cruft
* config for lively.modules
* some es6-interface changes, es6 interface is deprecated as it was merged into lively.modules!!!


text:
import chalk from 'chalk';
import tildify from 'tildify';
import path from 'path';
import ZiomLite from '../ziomLite';

const debugLog = ZiomLite.log.bind(null, chalk.yellow('ZIOM DEBUG'));
const dirname = path.resolve(__dirname + '/..');

export default function cmdDebug(argv, tasks, ziomInst, cliVersion) {
  debugLog('CLI __dirname', chalk.blue(tildify(dirname)));
  debugLog('Local __dirname', chalk.blue(tildify(ziomInst.Ziom.dirname)));
  debugLog('CLI version', chalk.blue(cliVersion));
  debugLog('Local version', chalk.blue(tildify(ziomInst.Ziom.version)));
  debugLog('CWD', chalk.blue(tildify(process.cwd())));
  if (argv) debugLog(chalk.blue('argv:'), argv);
  if (tasks && tasks.length) debugLog(chalk.blue('tasks:'), tasks);
  if (ziomInst) debugLog(chalk.blue('ziomfile:'), ziomInst);
}


text:
package org.jbehave.examples.core.stories;

import org.jbehave.core.annotations.BeforeStories;
import org.jbehave.core.configuration.Configuration;
import org.jbehave.core.embedder.StoryControls;
import org.jbehave.core.steps.InjectableStepsFactory;
import org.jbehave.core.steps.InstanceStepsFactory;
import org.jbehave.examples.core.CoreStory;
import org.jbehave.examples.core.service.TradingService;
import org.jbehave.examples.core.steps.TraderSteps;

public class FailingBeforeStories extends CoreStory {

    @Override
    public Configuration configuration() {
        return super.configuration().useStoryControls(new StoryControls().doResetStateBeforeStory(false).doResetStateBeforeScenario(false));
    }

    @Override
    public InjectableStepsFactory stepsFactory() {
        return new InstanceStepsFactory(configuration(), new TraderSteps(new TradingService()), this);
    }

    @BeforeStories
    public void beforeStories(){
        throw new RuntimeException("Bum go the stories");
    }
}


text:
#region Licence

#endregion

using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Diagnostics;

namespace WmcSoft.Configuration
{
    [DebuggerDisplay("{Name,nq} => {Type,nq}")]
    public abstract class FactoryElement<T> : ConfigurationElement
    {
        private readonly NameValueCollection parameters = new NameValueCollection(StringComparer.Ordinal);

        protected override ConfigurationPropertyCollection Properties {
            get {
                var properties = base.Properties;
                if (!properties.Contains("name"))
                    properties.Add(new ConfigurationProperty("name", typeof(string), null, ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey));
                if (!properties.Contains("type"))
                    properties.Add(new ConfigurationProperty("type", typeof(Type), typeof(T), new TypeNameConverter(), new SubclassTypeValidator(typeof(T)), ConfigurationPropertyOptions.IsRequired));
                return properties;
            }
        }

        public string Name {
            get { return (string)this["name"]; }
            set { this["name"] = value; }
        }

        public Type Type {
            get { return (Type)this["type"]; }
            set { this["type"] = value; }
        }

        public NameValueCollection Parameters => parameters;

        protected override bool OnDeserializeUnrecognizedAttribute(string name, string value)
        {
            Parameters[name] = value;
            return true;
        }

        public virtual T CreateInstance(params object[] args)
        {
            var type = Type;
            return (T)Activator.CreateInstance(type, args);
        }
    }
}


text:
const scrounge_node = require('./scrounge_node'),
      scrounge_elem = require('./scrounge_elem'),
      scrounge_file = require('./scrounge_file');

module.exports = (o => {
  // each scrounge element may define _array_ of rootname
  // removes duplicates. flattens array. unoptimised.
  o.getcontentrootnamearr = content =>
    scrounge_elem.getelemarr(content).reduce((prev, cur) => (
      prev.concat(scrounge_elem.getrootarr(cur))
    ), []).sort().filter((val, i, arr) => (
      arr.slice(i + 1).indexOf(val) === -1));

  o.getrootnamearr = (opts, filepath, fn) =>
    scrounge_file.read(opts, filepath, (err, content) => (
      fn(err, err || o.getcontentrootnamearr(content))));

  // updates a single element in the content, usually a timestamp.
  // used when a file is updated, scrounge will process the file
  // and update the timestamp forcing browser to load new script
  //
  // this
  //     <script src="./cjsnode.js?ts=12345" type="text/javascript"></script>
  //
  // becomes this
  //     <script src="./cjsnode.js?ts=45678" type="text/javascript"></script>
  //
  o.writecontentelemone = (opts, content, node) => {
    let scriptpath = scrounge_file
          .setpublicoutputpath(opts, node.get('filepath'), node.get('uid')),
        scriptsre = new RegExp(
          `${scriptpath.replace(/\.[^.]*$/, '')}.*(ts=[0-9]*)`, 'g');

    return content.replace(scriptsre, (a, b) => (
      a.replace(b, `ts=${opts.buildts}`)));
  };

  // read basepage and udpdate single elem timestampe only
  o.writeelemone = (opts, filepath, node, fn) => {
    scrounge_file.read(opts, filepath, (err, content) => {
      if (err) return fn(err);

      content = o.writecontentelemone(opts, content, node);

      scrounge_file.write(opts, filepath, content, fn);
    });
  };

  o.writeelemarr = (opts, filepath, elemarr, nodearrobj, fn) => {
    scrounge_file.read(opts, filepath, (err, content) => {
      if (err) return fn(err);

      let newcontent = scrounge_elem.getelemarr(content).reduce((content, elem) => {
        let indent = scrounge_elem.getindentation(elem);

        return content.replace(elem, scrounge_elem.getpopulated(
          elem, scrounge_elem.getrootarr(elem).filter(root => (
            // only operate on rootnames with an associated nodearr
            nodearrobj[root] && nodearrobj[root].length
          )).map(root => (
            // each node in the array returns ordered listing of elements
            scrounge_node.arrgetincludetagarr(opts, nodearrobj[root], root)
              .map(elem => indent + elem).join('\n')
          )).join('\n')
        ));
      }, content);

      // if :scrounge.version appears in the template anywhere,
      // replace w/ optional 'version' definition
      newcontent = newcontent.replace(/:scrounge.version/gi, opts.version);

      scrounge_file.write(opts, filepath, newcontent, fn);
    });
  };

  return o;
})({});


text:
export interface TableContainerClasses {
    /** Styles applied to the root element. */
    root: string;
}
export declare type TableContainerClassKey = keyof TableContainerClasses;
export declare function getTableContainerUtilityClass(slot: string): string;
declare const tableContainerClasses: TableContainerClasses;
export default tableContainerClasses;