text:
package org.keycloak.protocol.oidc.endpoints;

import org.jboss.logging.Logger;
import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.HttpResponse;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.keycloak.OAuth2Constants;
import org.keycloak.OAuthErrorException;
import org.keycloak.authentication.AuthenticationProcessor;
import org.keycloak.authorization.AuthorizationProvider;
import org.keycloak.authorization.authorization.AuthorizationTokenService;
import org.keycloak.authorization.util.Tokens;
import org.keycloak.common.ClientConnection;
import org.keycloak.common.Profile;
import org.keycloak.common.constants.ServiceAccountConstants;
import org.keycloak.common.util.KeycloakUriBuilder;
import org.keycloak.constants.AdapterConstants;
import org.keycloak.events.Details;
import org.keycloak.events.Errors;
import org.keycloak.events.EventBuilder;
import org.keycloak.events.EventType;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.jose.jws.JWSInputException;
import org.keycloak.models.AuthenticatedClientSessionModel;
import org.keycloak.models.AuthenticationFlowModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.ClientScopeModel;
import org.keycloak.models.ClientSessionContext;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserSessionModel;
import org.keycloak.models.utils.AuthenticationFlowResolver;
import org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper;
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
import org.keycloak.protocol.oidc.TokenExchangeContext;
import org.keycloak.protocol.oidc.TokenExchangeProvider;
import org.keycloak.protocol.oidc.TokenManager;
import org.keycloak.protocol.oidc.grants.ciba.CibaGrantType;
import org.keycloak.protocol.oidc.grants.device.DeviceGrantType;
import org.keycloak.protocol.oidc.utils.AuthorizeClientUtil;
import org.keycloak.protocol.oidc.utils.OAuth2Code;
import org.keycloak.protocol.oidc.utils.OAuth2CodeParser;
import org.keycloak.protocol.oidc.utils.PkceUtils;
import org.keycloak.protocol.saml.JaxrsSAML2BindingBuilder;
import org.keycloak.protocol.saml.SamlClient;
import org.keycloak.protocol.saml.SamlProtocol;
import org.keycloak.rar.AuthorizationRequestContext;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.AccessTokenResponse;
import org.keycloak.representations.idm.authorization.AuthorizationRequest.Metadata;
import org.keycloak.saml.common.constants.JBossSAMLConstants;
import org.keycloak.saml.common.constants.JBossSAMLURIConstants;
import org.keycloak.saml.common.exceptions.ConfigurationException;
import org.keycloak.saml.common.exceptions.ProcessingException;
import org.keycloak.saml.common.util.DocumentUtil;
import org.keycloak.services.CorsErrorResponseException;
import org.keycloak.services.ServicesLogger;
import org.keycloak.services.Urls;
import org.keycloak.services.clientpolicy.ClientPolicyException;
import org.keycloak.services.clientpolicy.context.ResourceOwnerPasswordCredentialsContext;
import org.keycloak.services.clientpolicy.context.ServiceAccountTokenRequestContext;
import org.keycloak.services.clientpolicy.context.TokenRefreshContext;
import org.keycloak.services.clientpolicy.context.TokenRequestContext;
import org.keycloak.services.managers.AppAuthManager;
import org.keycloak.services.managers.AuthenticationManager;
import org.keycloak.services.managers.AuthenticationSessionManager;
import org.keycloak.services.managers.ClientManager;
import org.keycloak.services.managers.RealmManager;
import org.keycloak.services.resources.Cors;
import org.keycloak.services.util.AuthorizationContextUtil;
import org.keycloak.services.util.DefaultClientSessionContext;
import org.keycloak.services.util.MtlsHoKTokenUtil;
import org.keycloak.sessions.AuthenticationSessionModel;
import org.keycloak.sessions.RootAuthenticationSessionModel;
import org.keycloak.util.TokenUtil;
import org.keycloak.utils.ProfileHelper;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.ws.rs.Consumes;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.xml.namespace.QName;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Supplier;
import java.util.stream.Stream;

/**
 * @author Stian Thorgersen
 */
public class TokenEndpoint {

    private static final Logger logger = Logger.getLogger(TokenEndpoint.class);
    private MultivaluedMap<String, String> formParams;
    private ClientModel client;
    private Map<String, String> clientAuthAttributes;

    private enum Action {
        AUTHORIZATION_CODE, REFRESH_TOKEN, PASSWORD, CLIENT_CREDENTIALS, TOKEN_EXCHANGE, PERMISSION, OAUTH2_DEVICE_CODE, CIBA
    }

    @Context
    private KeycloakSession session;

    @Context
    private HttpRequest request;

    @Context
    private HttpResponse httpResponse;

    @Context
    private HttpHeaders headers;

    @Context
    private ClientConnection clientConnection;

    private final TokenManager tokenManager;
    private final RealmModel realm;
    private final EventBuilder event;

    private Action action;

    private String grantType;

    private Cors cors;

    public TokenEndpoint(TokenManager tokenManager, RealmModel realm, EventBuilder event) {
        this.tokenManager = tokenManager;
        this.realm = realm;
        this.event = event;
    }

    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @POST
    public Response processGrantRequest() {
        cors = Cors.add(request).auth().allowedMethods("POST").auth().exposedHeaders(Cors.ACCESS_CONTROL_ALLOW_METHODS);

        MultivaluedMap<String, String> formParameters = request.getDecodedFormParameters();

        if (formParameters == null) {
            formParameters = new MultivaluedHashMap<>();
        }

        formParams = formParameters;
        grantType = formParams.getFirst(OIDCLoginProtocol.GRANT_TYPE_PARAM);

        // https://tools.ietf.org/html/rfc6749#section-5.1
        // The authorization server MUST include the HTTP "Cache-Control" response header field
        // with a value of "no-store" as well as the "Pragma" response header field with a value of "no-cache".
        MultivaluedMap<String, Object> outputHeaders = httpResponse.getOutputHeaders();
        outputHeaders.putSingle("Cache-Control", "no-store");
        outputHeaders.putSingle("Pragma", "no-cache");

        checkSsl();
        checkRealm();
        checkGrantType();

        if (!action.equals(Action.PERMISSION)) {
            checkClient();
            checkParameterDuplicated();
        }

        switch (action) {
            case AUTHORIZATION_CODE:
                return codeToToken();
            case REFRESH_TOKEN:
                return refreshTokenGrant();
            case PASSWORD:
                return resourceOwnerPasswordCredentialsGrant();
            case CLIENT_CREDENTIALS:
                return clientCredentialsGrant();
            case TOKEN_EXCHANGE:
                return tokenExchange();
            case PERMISSION:
                return permissionGrant();
            case OAUTH2_DEVICE_CODE:
                return oauth2DeviceCodeToToken();
            case CIBA:
                return cibaGrant();
        }

        throw new RuntimeException("Unknown action " + action);
    }

    @Path("introspect")
    public Object introspect() {
        TokenIntrospectionEndpoint tokenIntrospectionEndpoint = new TokenIntrospectionEndpoint(this.realm, this.event);

        ResteasyProviderFactory.getInstance().injectProperties(tokenIntrospectionEndpoint);

        return tokenIntrospectionEndpoint;
    }

    @OPTIONS
    public Response preflight() {
        if (logger.isDebugEnabled()) {
            logger.debugv("CORS preflight from: {0}", headers.getRequestHeaders().getFirst("Origin"));
        }
        return Cors.add(request, Response.ok()).auth().preflight().allowedMethods("POST", "OPTIONS").build();
    }

    private void checkSsl() {
        if (!session.getContext().getUri().getBaseUri().getScheme().equals("https") && realm.getSslRequired().isRequired(clientConnection)) {
            throw new CorsErrorResponseException(cors.allowAllOrigins(), OAuthErrorException.INVALID_REQUEST, "HTTPS required", Response.Status.FORBIDDEN);
        }
    }

    private void checkRealm() {
        if (!realm.isEnabled()) {
            throw new CorsErrorResponseException(cors.allowAllOrigins(), "access_denied", "Realm not enabled", Response.Status.FORBIDDEN);
        }
    }

    private void checkClient() {
        AuthorizeClientUtil.ClientAuthResult clientAuth = AuthorizeClientUtil.authorizeClient(session, event, cors);
        client = clientAuth.getClient();
        clientAuthAttributes = clientAuth.getClientAuthAttributes();

        cors.allowedOrigins(session, client);

        if (client.isBearerOnly()) {
            throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_CLIENT, "Bearer-only not allowed", Response.Status.BAD_REQUEST);
        }

    }

    private void checkGrantType() {
        if (grantType == null) {
            throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST, "Missing form parameter: " + OIDCLoginProtocol.GRANT_TYPE_PARAM, Response.Status.BAD_REQUEST);
        }

        if (grantType.equals(OAuth2Constants.AUTHORIZATION_CODE)) {
            event.event(EventType.CODE_TO_TOKEN);
            action = Action.AUTHORIZATION_CODE;
        } else if (grantType.equals(OAuth2Constants.REFRESH_TOKEN)) {
            event.event(EventType.REFRESH_TOKEN);
            action = Action.REFRESH_TOKEN;
        } else if (grantType.equals(OAuth2Constants.PASSWORD)) {
            event.event(EventType.LOGIN);
            action = Action.PASSWORD;
        } else if (grantType.equals(OAuth2Constants.CLIENT_CREDENTIALS)) {
            event.event(EventType.CLIENT_LOGIN);
            action = Action.CLIENT_CREDENTIALS;
        } else if (grantType.equals(OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE)) {
            event.event(EventType.TOKEN_EXCHANGE);
            action = Action.TOKEN_EXCHANGE;
        } else if (grantType.equals(OAuth2Constants.UMA_GRANT_TYPE)) {
            event.event(EventType.PERMISSION_TOKEN);
            action = Action.PERMISSION;
        } else if (grantType.equals(OAuth2Constants.DEVICE_CODE_GRANT_TYPE)) {
            event.event(EventType.OAUTH2_DEVICE_CODE_TO_TOKEN);
            action = Action.OAUTH2_DEVICE_CODE;
        } else if (grantType.equals(OAuth2Constants.CIBA_GRANT_TYPE)) {
            event.event(EventType.AUTHREQID_TO_TOKEN);
            action = Action.CIBA;
        } else {
            throw new CorsErrorResponseException(cors, OAuthErrorException.UNSUPPORTED_GRANT_TYPE,
                "Unsupported " + OIDCLoginProtocol.GRANT_TYPE_PARAM, Response.Status.BAD_REQUEST);
        }

        event.detail(Details.GRANT_TYPE, grantType);
    }

    private void checkParameterDuplicated() {
        for (String key : formParams.keySet()) {
            if (formParams.get(key).size() != 1) {
                throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST, "duplicated parameter",
                    Response.Status.BAD_REQUEST);
            }
        }
    }

    public Response codeToToken() {
        String code = formParams.getFirst(OAuth2Constants.CODE);
        if (code == null) {
            event.error(Errors.INVALID_CODE);
            throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST, "Missing parameter: " + OAuth2Constants.CODE, Response.Status.BAD_REQUEST);
        }

        OAuth2CodeParser.ParseResult parseResult = OAuth2CodeParser.parseCode(session, code, realm, event);
        if (parseResult.isIllegalCode()) {
            AuthenticatedClientSessionModel clientSession = parseResult.getClientSession();

            // Attempt to use same code twice should invalidate existing clientSession
            if (clientSession != null) {
                clientSession.detachFromUserSession();
            }

            event.error(Errors.INVALID_CODE);

            throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Code not valid", Response.Status.BAD_REQUEST);
        }

        AuthenticatedClientSessionModel clientSession = parseResult.getClientSession();

        if (parseResult.isExpiredCode()) {
            event.error(Errors.EXPIRED_CODE);
            throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Code is expired", Response.Status.BAD_REQUEST);
        }

        UserSessionModel userSession = null;
        if (clientSession != null) {
            userSession = clientSession.getUserSession();
        }

        if (userSession == null) {
            event.error(Errors.USER_SESSION_NOT_FOUND);
            throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "User session not found", Response.Status.BAD_REQUEST);
        }

        UserModel user = userSession.getUser();
        if (user == null) {
            event.error(Errors.USER_NOT_FOUND);
            throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "User not found", Response.Status.BAD_REQUEST);
        }

        event.user(userSession.getUser());

        if (!user.isEnabled()) {
            event.error(Errors.USER_DISABLED);
            throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "User disabled", Response.Status.BAD_REQUEST);
        }

        OAuth2Code codeData = parseResult.getCodeData();
        String redirectUri = codeData.getRedirectUriParam();
        String redirectUriParam = formParams.getFirst(OAuth2Constants.REDIRECT_URI);

        // KEYCLOAK-4478 Backwards compatibility with the adapters earlier than KC 3.4.2
        if (redirectUriParam != null && redirectUriParam.contains("session_state=") && !redirectUri.contains("session_state=")) {
            redirectUriParam = KeycloakUriBuilder.fromUri(redirectUriParam)
                    .replaceQueryParam(OAuth2Constants.SESSION_STATE, null)
                    .build().toString();
        }

        if (redirectUri != null && !redirectUri.equals(redirectUriParam)) {
            event.error(Errors.INVALID_CODE);
            throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Incorrect redirect_uri", Response.Status.BAD_REQUEST);
        }

        if (!client.getClientId().equals(clientSession.getClient().getClientId())) {
            event.error(Errors.INVALID_CODE);
            throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Auth error", Response.Status.BAD_REQUEST);
        }

        if (!client.isStandardFlowEnabled()) {
            event.error(Errors.NOT_ALLOWED);
            throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Client not allowed to exchange code", Response.Status.BAD_REQUEST);
        }

        if (!AuthenticationManager.isSessionValid(realm, userSession)) {
            event.error(Errors.USER_SESSION_NOT_FOUND);
            throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Session not active", Response.Status.BAD_REQUEST);
        }

        // https://tools.ietf.org/html/rfc7636#section-4.6
        String codeVerifier = formParams.getFirst(OAuth2Constants.CODE_VERIFIER);
        String codeChallenge = codeData.getCodeChallenge();
        String codeChallengeMethod = codeData.getCodeChallengeMethod();
        String authUserId = user.getId();
        String authUsername = user.getUsername();
        if (authUserId == null) {
            authUserId = "unknown";
        }
        if (authUsername == null) {
            authUsername = "unknown";
        }

        if (codeChallengeMethod != null && !codeChallengeMethod.isEmpty()) {
            PkceUtils.checkParamsForPkceEnforcedClient(codeVerifier, codeChallenge, codeChallengeMethod, authUserId, authUsername, event, cors);
        } else {
            // PKCE Activation is OFF, execute the codes implemented in KEYCLOAK-2604
            PkceUtils.checkParamsForPkceNotEnforcedClient(codeVerifier, codeChallenge, codeChallengeMethod, authUserId, authUsername, event, cors);
        }

        try {
            session.clientPolicy().triggerOnEvent(new TokenRequestContext(formParams, parseResult));
        } catch (ClientPolicyException cpe) {
            event.error(cpe.getError());
            throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
        }

        updateClientSession(clientSession);
        updateUserSessionFromClientAuth(userSession);

        // Compute client scopes again from scope parameter. Check if user still has them granted
        // (but in code-to-token request, it could just theoretically happen that they are not available)
        String scopeParam = codeData.getScope();
        Supplier<Stream<ClientScopeModel>> clientScopesSupplier = () -> TokenManager.getRequestedClientScopes(scopeParam, client);
        if (!TokenManager.verifyConsentStillAvailable(session, user, client, clientScopesSupplier.get())) {
            event.error(Errors.NOT_ALLOWED);
            throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_SCOPE, "Client no longer has requested consent from user", Response.Status.BAD_REQUEST);
        }

        ClientSessionContext clientSessionCtx = DefaultClientSessionContext.fromClientSessionAndScopeParameter(clientSession, scopeParam, session);

        // Set nonce as an attribute in the ClientSessionContext. Will be used for the token generation
        clientSessionCtx.setAttribute(OIDCLoginProtocol.NONCE_PARAM, codeData.getNonce());

        return createTokenResponse(user, userSession, clientSessionCtx, scopeParam, true);
    }

    public Response createTokenResponse(UserModel user, UserSessionModel userSession, ClientSessionContext clientSessionCtx,
        String scopeParam, boolean code) {
        AccessToken token = tokenManager.createClientAccessToken(session, realm, client, user, userSession, clientSessionCtx);

        TokenManager.AccessTokenResponseBuilder responseBuilder = tokenManager
            .responseBuilder(realm, client, event, session, userSession, clientSessionCtx).accessToken(token);
        if (OIDCAdvancedConfigWrapper.fromClientModel(client).isUseRefreshToken()) {
            responseBuilder.generateRefreshToken();
        }

        checkMtlsHoKToken(responseBuilder, OIDCAdvancedConfigWrapper.fromClientModel(client).isUseRefreshToken());

        if (TokenUtil.isOIDCRequest(scopeParam)) {
            responseBuilder.generateIDToken().generateAccessTokenHash();
        }

        AccessTokenResponse res = null;
        if (code) {
            try {
                res = responseBuilder.build();
            } catch (RuntimeException re) {
                if ("can not get encryption KEK".equals(re.getMessage())) {
                    throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST,
                        "can not get encryption KEK", Response.Status.BAD_REQUEST);
                } else {
                    throw re;
                }
            }
        } else {
            res = responseBuilder.build();
        }
        event.success();

        return cors.builder(Response.ok(res).type(MediaType.APPLICATION_JSON_TYPE)).build();
    }

    private void checkMtlsHoKToken(TokenManager.AccessTokenResponseBuilder responseBuilder, boolean useRefreshToken) {
        // KEYCLOAK-6771 Certificate Bound Token
        // https://tools.ietf.org/html/draft-ietf-oauth-mtls-08#section-3
        if (OIDCAdvancedConfigWrapper.fromClientModel(client).isUseMtlsHokToken()) {
            AccessToken.CertConf certConf = MtlsHoKTokenUtil.bindTokenWithClientCertificate(request, session);
            if (certConf != null) {
                responseBuilder.getAccessToken().setCertConf(certConf);
                if (useRefreshToken) {
                    responseBuilder.getRefreshToken().setCertConf(certConf);
                }
            } else {
                event.error(Errors.INVALID_REQUEST);
                throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST,
                        "Client Certification missing for MTLS HoK Token Binding", Response.Status.BAD_REQUEST);
            }
        }
    }

    public Response refreshTokenGrant() {
        String refreshToken = formParams.getFirst(OAuth2Constants.REFRESH_TOKEN);
        if (refreshToken == null) {
            throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST, "No refresh token", Response.Status.BAD_REQUEST);
        }

        try {
            session.clientPolicy().triggerOnEvent(new TokenRefreshContext(formParams));
        } catch (ClientPolicyException cpe) {
            event.error(cpe.getError());
            throw new CorsErrorResponseException(cors, cpe.getError(), cpe.getErrorDetail(), cpe.getErrorStatus());
        }

        AccessTokenResponse res;
        try {
            // KEYCLOAK-6771 Certificate Bound Token
            TokenManager.RefreshResult result = tokenManager.refreshAccessToken(session, session.getContext().getUri(), clientConnection, realm, client, refreshToken, event, headers, request);
            res = result.getResponse();

            if (!result.isOfflineToken()) {
                UserSessionModel userSession = session.sessions().getUserSession(realm, res.getSessionState());
                AuthenticatedClientSessionModel clientSession = userSession.getAuthenticatedClientSessionByClient(client.getId());
                updateClientSession(clientSession);
                updateUserSessionFromClientAuth(userSession);
            }

        } catch (OAuthErrorException e) {
            logger.trace(e.getMessage(), e);
            // KEYCLOAK-6771 Certificate Bound Token
            if (MtlsHoKTokenUtil.CERT_VERIFY_ERROR_DESC.equals(e.getDescription())) {
                event.error(Errors.NOT_ALLOWED);
                throw new CorsErrorResponseException(cors, e.getError(), e.getDescription(), Response.Status.UNAUTHORIZED);
            } else {
                event.error(Errors.INVALID_TOKEN);
                throw new CorsErrorResponseException(cors, e.getError(), e.getDescription(), Response.Status.BAD_REQUEST);
            }
        }

        event.success();

        return cors.builder(Response.ok(res, MediaType.APPLICATION_JSON_TYPE)).build();
    }

    private void updateClientSession(AuthenticatedClientSessionModel clientSession) {

        if(clientSession == null) {
            ServicesLogger.LOGGER.clientSessionNull();
            return;
        }

        String adapterSessionId = formParams.getFirst(AdapterConstants.CLIENT_SESSION_STATE);
        if (adapterSessionId != null) {
            String adapterSessionHost = formParams.getFirst(AdapterConstants.CLIENT_SESSION_HOST);
            logger.debugf("Adapter Session '%s' saved in ClientSession for client '%s'. Host is '%s'", adapterSessionId, client.getClientId(), adapterSessionHost);

            String oldClientSessionState = clientSession.getNote(AdapterConstants.CLIENT_SESSION_STATE);
            if (!adapterSessionId.equals(oldClientSessionState)) {
                clientSession.setNote(AdapterConstants.CLIENT_SESSION_STATE, adapterSessionId);
            }

            String oldClientSessionHost = clientSession.getNote(AdapterConstants.CLIENT_SESSION_HOST);
            if (!Objects.equals(adapterSessionHost, oldClientSessionHost)) {
                clientSession.setNote(AdapterConstants.CLIENT_SESSION_HOST, adapterSessionHost);
            }
        }
    }

    private void updateUserSessionFromClientAuth(UserSessionModel userSession) {
        for (Map.Entry<String, String> attr : clientAuthAttributes.entrySet()) {
            userSession.setNote(attr.getKey(), attr.getValue());
        }
    }

    public Response resourceOwnerPasswordCredentialsGrant() {
        event.detail(Details.AUTH_METHOD, "oauth_credentials");

        if (!client.isDirectAccessGrantsEnabled()) {
            event.error(Errors.NOT_ALLOWED);
            throw new CorsErrorResponseException(cors, OAuthErrorException.UNAUTHORIZED_CLIENT, "Client not allowed for direct access grants", Response.Status.BAD_REQUEST);
        }

        if (client.isConsentRequired()) {
            event.error(Errors.CONSENT_DENIED);
            throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_CLIENT, "Client requires user consent", Response.Status.BAD_REQUEST);
        }

        try {
            session.clientPolicy().triggerOnEvent(new ResourceOwnerPasswordCredentialsContext(formParams));
        } catch (ClientPolicyException cpe) {
            event.error(cpe.getError());
            throw new CorsErrorResponseException(cors, cpe.getError(), cpe.getErrorDetail(), cpe.getErrorStatus());
        }

        String scope = getRequestedScopes();

        RootAuthenticationSessionModel rootAuthSession = new AuthenticationSessionManager(session).createAuthenticationSession(realm, false);
        AuthenticationSessionModel authSession = rootAuthSession.createAuthenticationSession(client);

        authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
        authSession.setAction(AuthenticatedClientSessionModel.Action.AUTHENTICATE.name());
        authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName()));
        authSession.setClientNote(OIDCLoginProtocol.SCOPE_PARAM, scope);

        AuthenticationFlowModel flow = AuthenticationFlowResolver.resolveDirectGrantFlow(authSession);
        String flowId = flow.getId();
        AuthenticationProcessor processor = new AuthenticationProcessor();
        processor.setAuthenticationSession(authSession)
                .setFlowId(flowId)
                .setConnection(clientConnection)
                .setEventBuilder(event)
                .setRealm(realm)
                .setSession(session)
                .setUriInfo(session.getContext().getUri())
                .setRequest(request);
        Response challenge = processor.authenticateOnly();
        if (challenge != null) {
            // Remove authentication session as "Resource Owner Password Credentials Grant" is single-request scoped authentication
            new AuthenticationSessionManager(session).removeAuthenticationSession(realm, authSession, false);
            cors.build(httpResponse);
            return challenge;
        }
        processor.evaluateRequiredActionTriggers();
        UserModel user = authSession.getAuthenticatedUser();
        if (user.getRequiredActionsStream().count() > 0 || authSession.getRequiredActions().size() > 0) {
            // Remove authentication session as "Resource Owner Password Credentials Grant" is single-request scoped authentication
            new AuthenticationSessionManager(session).removeAuthenticationSession(realm, authSession, false);
            event.error(Errors.RESOLVE_REQUIRED_ACTIONS);
            throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Account is not fully set up", Response.Status.BAD_REQUEST);

        }

        AuthenticationManager.setClientScopesInSession(authSession);

        ClientSessionContext clientSessionCtx = processor.attachSession();
        UserSessionModel userSession = processor.getUserSession();
        updateUserSessionFromClientAuth(userSession);

        TokenManager.AccessTokenResponseBuilder responseBuilder = tokenManager
            .responseBuilder(realm, client, event, session, userSession, clientSessionCtx).generateAccessToken();
        if (OIDCAdvancedConfigWrapper.fromClientModel(client).isUseRefreshToken()) {
            responseBuilder.generateRefreshToken();
        }

        String scopeParam = clientSessionCtx.getClientSession().getNote(OAuth2Constants.SCOPE);
        if (TokenUtil.isOIDCRequest(scopeParam)) {
            responseBuilder.generateIDToken().generateAccessTokenHash();
        }

        // TODO : do the same as codeToToken()
        AccessTokenResponse res = responseBuilder.build();

        event.success();
        AuthenticationManager.logSuccess(session, authSession);

        return cors.builder(Response.ok(res, MediaType.APPLICATION_JSON_TYPE)).build();
    }

    public Response clientCredentialsGrant() {
        if (client.isBearerOnly()) {
            event.error(Errors.INVALID_CLIENT);
            throw new CorsErrorResponseException(cors, OAuthErrorException.UNAUTHORIZED_CLIENT, "Bearer-only client not allowed to retrieve service account", Response.Status.UNAUTHORIZED);
        }
        if (client.isPublicClient()) {
            event.error(Errors.INVALID_CLIENT);
            throw new CorsErrorResponseException(cors, OAuthErrorException.UNAUTHORIZED_CLIENT, "Public client not allowed to retrieve service account", Response.Status.UNAUTHORIZED);
        }
        if (!client.isServiceAccountsEnabled()) {
            event.error(Errors.INVALID_CLIENT);
            throw new CorsErrorResponseException(cors, OAuthErrorException.UNAUTHORIZED_CLIENT, "Client not enabled to retrieve service account", Response.Status.UNAUTHORIZED);
        }

        UserModel clientUser = session.users().getServiceAccount(client);

        if (clientUser == null || client.getProtocolMapperByName(OIDCLoginProtocol.LOGIN_PROTOCOL, ServiceAccountConstants.CLIENT_ID_PROTOCOL_MAPPER) == null) {
            // May need to handle bootstrap here as well
            logger.debugf("Service account user for client '%s' not found or default protocol mapper for service account not found. Creating now", client.getClientId());
            new ClientManager(new RealmManager(session)).enableServiceAccount(client);
            clientUser = session.users().getServiceAccount(client);
        }

        String clientUsername = clientUser.getUsername();
        event.detail(Details.USERNAME, clientUsername);
        event.user(clientUser);

        if (!clientUser.isEnabled()) {
            event.error(Errors.USER_DISABLED);
            throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST, "User '" + clientUsername + "' disabled", Response.Status.UNAUTHORIZED);
        }

        String scope = getRequestedScopes();

        RootAuthenticationSessionModel rootAuthSession = new AuthenticationSessionManager(session).createAuthenticationSession(realm, false);
        AuthenticationSessionModel authSession = rootAuthSession.createAuthenticationSession(client);

        authSession.setAuthenticatedUser(clientUser);
        authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
        authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName()));
        authSession.setClientNote(OIDCLoginProtocol.SCOPE_PARAM, scope);

        // persisting of userSession by default
        UserSessionModel.SessionPersistenceState sessionPersistenceState = UserSessionModel.SessionPersistenceState.PERSISTENT;

        boolean useRefreshToken = OIDCAdvancedConfigWrapper.fromClientModel(client).isUseRefreshTokenForClientCredentialsGrant();
        if (!useRefreshToken) {
            // we don't want to store a session hence we mark it as transient, see KEYCLOAK-9551
            sessionPersistenceState = UserSessionModel.SessionPersistenceState.TRANSIENT;
        }

        UserSessionModel userSession = session.sessions().createUserSession(authSession.getParentSession().getId(), realm, clientUser, clientUsername,
                clientConnection.getRemoteAddr(), ServiceAccountConstants.CLIENT_AUTH, false, null, null, sessionPersistenceState);
        event.session(userSession);

        AuthenticationManager.setClientScopesInSession(authSession);
        ClientSessionContext clientSessionCtx = TokenManager.attachAuthenticationSession(session, userSession, authSession);

        // Notes about client details
        userSession.setNote(ServiceAccountConstants.CLIENT_ID, client.getClientId());
        userSession.setNote(ServiceAccountConstants.CLIENT_HOST, clientConnection.getRemoteHost());
        userSession.setNote(ServiceAccountConstants.CLIENT_ADDRESS, clientConnection.getRemoteAddr());

        try {
            session.clientPolicy().triggerOnEvent(new ServiceAccountTokenRequestContext(formParams, clientSessionCtx.getClientSession()));
        } catch (ClientPolicyException cpe) {
            event.error(cpe.getError());
            throw new CorsErrorResponseException(cors, cpe.getError(), cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
        }

        updateUserSessionFromClientAuth(userSession);

        TokenManager.AccessTokenResponseBuilder responseBuilder = tokenManager.responseBuilder(realm, client, event, session, userSession, clientSessionCtx)
                .generateAccessToken();

        // Make refresh token generation optional, see KEYCLOAK-9551
        if (useRefreshToken) {
            responseBuilder = responseBuilder.generateRefreshToken();
        } else {
            responseBuilder.getAccessToken().setSessionState(null);
        }

        checkMtlsHoKToken(responseBuilder, useRefreshToken);

        String scopeParam = clientSessionCtx.getClientSession().getNote(OAuth2Constants.SCOPE);
        if (TokenUtil.isOIDCRequest(scopeParam)) {
            responseBuilder.generateIDToken().generateAccessTokenHash();
        }

        // TODO : do the same as codeToToken()
        AccessTokenResponse res = responseBuilder.build();

        event.success();

        return cors.builder(Response.ok(res, MediaType.APPLICATION_JSON_TYPE)).build();
    }

    private String getRequestedScopes() {
        String scope = formParams.getFirst(OAuth2Constants.SCOPE);

        boolean validScopes;
        if (Profile.isFeatureEnabled(Profile.Feature.DYNAMIC_SCOPES)) {
            AuthorizationRequestContext authorizationRequestContext = AuthorizationContextUtil.getAuthorizationRequestContextFromScopes(session, scope);
            validScopes = TokenManager.isValidScope(scope, authorizationRequestContext, client);
        } else {
            validScopes = TokenManager.isValidScope(scope, client);
        }

        if (!validScopes) {
            event.error(Errors.INVALID_REQUEST);
            throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_SCOPE, "Invalid scopes: " + scope,
                    Status.BAD_REQUEST);
        }

        return scope;
    }

    public Response tokenExchange() {
        ProfileHelper.requireFeature(Profile.Feature.TOKEN_EXCHANGE);

        event.detail(Details.AUTH_METHOD, "token_exchange");
        event.client(client);

        TokenExchangeContext context = new TokenExchangeContext(
                session,
                formParams,
                cors,
                realm,
                event,
                client,
                clientConnection,
                headers,
                tokenManager,
                clientAuthAttributes);

        return session.getKeycloakSessionFactory()
                .getProviderFactoriesStream(TokenExchangeProvider.class)
                .sorted((f1, f2) -> f2.order() - f1.order())
                .map(f -> session.getProvider(TokenExchangeProvider.class, f.getId()))
                .filter(p -> p.supports(context))
                .findFirst()
                .orElseThrow(() -> new InternalServerErrorException("No token exchange provider available"))
                .exchange(context);
    }

    public Response permissionGrant() {
        event.detail(Details.AUTH_METHOD, "oauth_credentials");

        String accessTokenString = null;
        String authorizationHeader = headers.getRequestHeaders().getFirst(HttpHeaders.AUTHORIZATION);

        if (authorizationHeader != null && authorizationHeader.toLowerCase().startsWith("bearer")) {
            accessTokenString = new AppAuthManager().extractAuthorizationHeaderToken(headers);
        }

        // we allow public clients to authenticate using a bearer token, where the token should be a valid access token.
        // public clients don't have secret and should be able to obtain a RPT by providing an access token previously issued by the server
        if (accessTokenString != null) {
            AccessToken accessToken = Tokens.getAccessToken(session);

            if (accessToken == null) {
                try {
                    // In case the access token is invalid because it's expired or the user is disabled, identify the client
                    // from the access token anyway in order to set correct CORS headers.
                    AccessToken invalidToken = new JWSInput(accessTokenString).readJsonContent(AccessToken.class);
                    ClientModel client = realm.getClientByClientId(invalidToken.getIssuedFor());
                    cors.allowedOrigins(session, client);
                    event.client(client);
                } catch (JWSInputException ignore) {
                }
                event.error(Errors.INVALID_TOKEN);
                throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Invalid bearer token", Status.UNAUTHORIZED);
            }

            ClientModel client = realm.getClientByClientId(accessToken.getIssuedFor());

            session.getContext().setClient(client);

            cors.allowedOrigins(session, client);
            event.client(client);
        }

        String claimToken = null;

        // claim_token is optional, if provided we just grab it from the request
        if (formParams.containsKey("claim_token")) {
            claimToken = formParams.get("claim_token").get(0);
        }

        String claimTokenFormat = formParams.getFirst("claim_token_format");

        if (claimToken != null && claimTokenFormat == null) {
            claimTokenFormat = AuthorizationTokenService.CLAIM_TOKEN_FORMAT_ID_TOKEN;
        }

        String subjectToken = formParams.getFirst("subject_token");

        if (accessTokenString == null) {
            // in case no bearer token is provided, we force client authentication
            checkClient();

            // if a claim token is provided, we check if the format is a OpenID Connect IDToken and assume the token represents the identity asking for permissions
            if (AuthorizationTokenService.CLAIM_TOKEN_FORMAT_ID_TOKEN.equalsIgnoreCase(claimTokenFormat)) {
                accessTokenString = claimToken;
            } else if (subjectToken != null) {
                accessTokenString = subjectToken;
            } else {
                // Clients need to authenticate in order to obtain a RPT from the server.
                // In order to support cases where the client is obtaining permissions on its on behalf, we issue a temporary access token
                accessTokenString = AccessTokenResponse.class.cast(clientCredentialsGrant().getEntity()).getToken();
            }
        }

        AuthorizationTokenService.KeycloakAuthorizationRequest authorizationRequest = new AuthorizationTokenService.KeycloakAuthorizationRequest(session.getProvider(AuthorizationProvider.class),
                tokenManager, event, this.request, cors, clientConnection);

        authorizationRequest.setTicket(formParams.getFirst("ticket"));
        authorizationRequest.setClaimToken(claimToken);
        authorizationRequest.setClaimTokenFormat(claimTokenFormat);
        authorizationRequest.setPct(formParams.getFirst("pct"));

        String rpt = formParams.getFirst("rpt");

        if (rpt != null) {
            AccessToken accessToken = session.tokens().decode(rpt, AccessToken.class);
            if (accessToken == null) {
                event.error(Errors.INVALID_REQUEST);
                throw new CorsErrorResponseException(cors, "invalid_rpt", "RPT signature is invalid", Status.FORBIDDEN);
            }

            authorizationRequest.setRpt(accessToken);
        }

        authorizationRequest.setScope(formParams.getFirst("scope"));
        String audienceParam = formParams.getFirst("audience");
        authorizationRequest.setAudience(audienceParam);
        authorizationRequest.setSubjectToken(accessTokenString);

        event.detail(Details.AUDIENCE, audienceParam);

        String submitRequest = formParams.getFirst("submit_request");

        authorizationRequest.setSubmitRequest(submitRequest == null ? true : Boolean.valueOf(submitRequest));

        // permissions have a format like RESOURCE#SCOPE1,SCOPE2
        List<String> permissions = formParams.get("permission");

        if (permissions != null) {
            event.detail(Details.PERMISSION, String.join("|", permissions));
            for (String permission : permissions) {
                String[] parts = permission.split("#");
                String resource = parts[0];

                if (parts.length == 1) {
                    authorizationRequest.addPermission(resource);
                } else {
                    String[] scopes = parts[1].split(",");
                    authorizationRequest.addPermission(parts[0], scopes);
                }
            }
        }

        Metadata metadata = new Metadata();

        String responseIncludeResourceName = formParams.getFirst("response_include_resource_name");

        if (responseIncludeResourceName != null) {
            metadata.setIncludeResourceName(Boolean.parseBoolean(responseIncludeResourceName));
        }

        String responsePermissionsLimit = formParams.getFirst("response_permissions_limit");

        if (responsePermissionsLimit != null) {
            metadata.setLimit(Integer.parseInt(responsePermissionsLimit));
        }

        metadata.setResponseMode(formParams.getFirst("response_mode"));

        authorizationRequest.setMetadata(metadata);

        Response authorizationResponse = AuthorizationTokenService.instance().authorize(authorizationRequest);

        event.success();

        return authorizationResponse;
    }

    public Response oauth2DeviceCodeToToken() {
        DeviceGrantType deviceGrantType = new DeviceGrantType(formParams, client, session, this, realm, event, cors);
        return deviceGrantType.oauth2DeviceFlow();
    }

    public Response cibaGrant() {
        CibaGrantType grantType = new CibaGrantType(formParams, client, session, this, realm, event, cors);
        return grantType.cibaGrant();
    }

    public static class TokenExchangeSamlProtocol extends SamlProtocol {

        final SamlClient samlClient;

        public TokenExchangeSamlProtocol(SamlClient samlClient) {
            this.samlClient = samlClient;
        }

        @Override
        protected Response buildAuthenticatedResponse(AuthenticatedClientSessionModel clientSession, String redirectUri,
                                                      Document samlDocument, JaxrsSAML2BindingBuilder bindingBuilder)
                throws ConfigurationException, ProcessingException, IOException {
            JaxrsSAML2BindingBuilder.PostBindingBuilder builder = bindingBuilder.postBinding(samlDocument);

            Element assertionElement;
            if (samlClient.requiresEncryption()) {
                assertionElement = DocumentUtil.getElement(builder.getDocument(), new QName(JBossSAMLURIConstants.ASSERTION_NSURI.get(), JBossSAMLConstants.ENCRYPTED_ASSERTION.get()));
            } else {
                assertionElement = DocumentUtil.getElement(builder.getDocument(), new QName(JBossSAMLURIConstants.ASSERTION_NSURI.get(), JBossSAMLConstants.ASSERTION.get()));
            }
            if (assertionElement == null) {
                return Response.status(Status.BAD_REQUEST).build();
            }
            String assertion = DocumentUtil.getNodeAsString(assertionElement);
            return Response.ok(assertion, MediaType.APPLICATION_XML_TYPE).build();
        }

        @Override
        protected Response buildErrorResponse(boolean isPostBinding, String destination, JaxrsSAML2BindingBuilder binding, Document document) throws ConfigurationException, ProcessingException, IOException {
            return Response.status(Status.BAD_REQUEST).build();
        }
    }
}


text:
!Update: This skin is for CKeditor3 use. Want the new CKeditor4 skin? https://github.com/Kunstmaan/BootstrapCK4-Skin

The [BootstrapCK-Skin][BootstrapCK-Skin] is a skin for [CKEditor][CKEditor] based on [Twitter Bootstrap][Twitter Bootstrap] styles.

Some things couldn't be changed inside the skin, like the smileys and the position of the browse buttons when inserting an image or a flash.

Here's how you fix that:

## Smileys

Go to plugins > smiley > dialogs , and replace smiley.js with [this one][this one].

And grab your new images over [here][here].

## Browse buttons

Go to plugins > image > dialogs > image.js and to plugins > flash > dialogs > flash.js

In both, change the margin-top to 17px (instead of 10px).

# Demo
[http://kunstmaan.github.com/BootstrapCK-Skin/][http://kunstmaan.github.com/BootstrapCK-Skin/]

[BootstrapCK-Skin]: https://github.com/Kunstmaan/BootstrapCK-Skin "BootstrapCK-Skin"
[CKEditor]: http://ckeditor.com/ "CKEditor"
[Twitter Bootstrap]: http://twitter.github.com/bootstrap/ "Twitter Bootstrap"
[this one]: http://kunstmaan.github.com/BootstrapCK-Skin/smiley.js "smiley.js"
[here]: http://kunstmaan.github.com/BootstrapCK-Skin/smileys.zip "smileys.zip"
[http://kunstmaan.github.com/BootstrapCK-Skin/]: http://kunstmaan.github.com/BootstrapCK-Skin/ "Demo"
[kunstmaan]: http://www.kunstmaan.be "Kunstmaan"

redpajama_set_name: RedPajamaGithub


text:
static const NSString *kAppId	= @"app_id";

typedef void (^loanRequestCompletionHandler)(BOOL success, NSArray *loans, NSError *error);
typedef void (^imageRequestCompletionHandler)(BOOL success, UIImage *image, NSError *error);
typedef void (^partnerRequestCompletionHandler)(BOOL success, NSArray *partners, NSError *error);
typedef void (^lendersRequestCompletionHandler)(BOOL success, NSArray *lenders, NSError *error);
typedef void (^teamsRequestCompletionHandler)(BOOL success, NSArray *teams, NSError *error);

@interface KivaRequestManager : NSObject

//Loan Requests
+ (void)sendLoanRequest:(KivaLoanRequest *)request
	withCompletionHandler:(loanRequestCompletionHandler)completionHandler;

//Image Requests (could use SDWebImage or something similar also)
+ (void)fetchImage:(KivaImage *)image forSize:(ImageSize)size
	withCompletionHandler:(imageRequestCompletionHandler)completionHandler;

+ (void)sendPartnerRequest:(KivaPartnerRequest *)request
	 withCompletionHandler:(partnerRequestCompletionHandler)completionHandler;

+ (void)sendLenderRequest:(KivaLenderRequest *)request
	withCompletionHandler:(lendersRequestCompletionHandler)completionHandler;

+ (void)sendTeamRequest:(KivaTeamRequest *)request
  withCompletionHandler:(teamsRequestCompletionHandler)completionHandler;

+ (void)addAppId:(NSString *)appId;
+ (NSString *)appID;

@end


text:
const Account = require('../account')
const Chain = require('../chain')
const test = require('tape')

const f = require('./fixtures/account')
f.allAddresses = [].concat.apply([], f.addresses)

function blankAccount (json) {
  const account = Account.fromJSON(json)
  const chains = account.chains.map(function (chain) {
    return new Chain(chain.__parent, 0)
  })

  return new Account(chains)
}

test('containsAddress', function (t) {
  const account = Account.fromJSON(f.neutered.json)

  f.allAddresses.forEach(function (address) {
    t.equal(account.containsAddress(address), true, 'returns true for known chain address')
  })

  t.equal(account.containsAddress('mpFZW4A9QtRuSpuh9SmeW7RSzFE3TgB8Ko'), false, 'returns false for unknown address')
  t.end()
})

test('clone', function (t) {
  const account = Account.fromJSON(f.neutered.json)
  const clone = account.clone()

  // by reference
  t.equal(account.chains.length, clone.chains.length, 'same number of chains')
  t.notEqual(account.chains, clone.chains, 'chain arrays are different arrays')
  t.same(account.chains, clone.chains, 'chains are deep copied')
  for (let i = 0; i < account.chains.length; ++i) {
    t.notEqual(account.chains[i], clone.chains[i], 'chains are different objects')
  }

  account.nextChainAddress(1)
  t.notSame(account.chains, clone.chains, 'chains now diverge, 1 has an extra address')
  t.end()
})

test('discoverChain', function (t) {
  const account = Account.fromJSON(f.neutered.json)
  const before = account.getChainAddress(0)
  const after = account.getChain(0).clone().next()

  t.test('does not mutate the chain during discovery', function (t) {
    t.plan(2)

    account.discoverChain(0, 20, function (addresses, callback) {
      const tmpAddrs = addresses.map(function (address) {
        // account.containsAddress would return true if internally the chain was iterating
        return address !== before && account.containsAddress(address)
      })

      const addrs = {}

      for (const add in tmpAddrs) {
        addrs[addresses[add]] = tmpAddrs[add]
      }

      return callback(null, addrs)
    }, function (err) {
      t.ifErr(err, 'no error')
      t.equal(account.getChainAddress(0), before, 'internal chain was unchanged')
    })
  })

  t.test('does mutate the chain post-discovery', function (t) {
    t.plan(2)

    account.discoverChain(0, 20, function (addresses, callback) {
      const tmpAddrs = addresses.map(function (address) {
        // account.containsAddress would return true if internally the chain was iterating
        return account.containsAddress(address)
      })

      const addrs = {}

      for (const add in tmpAddrs) {
        addrs[addresses[add]] = tmpAddrs[add]
      }

      return callback(null, addrs)
    }, function (err) {
      t.ifErr(err, 'no error')
      t.equal(account.getChainAddress(0), after, 'internal chain iterated forward one address')
    })
  })
})

test('getAllAddresses', function (t) {
  const account = blankAccount(f.neutered.json)

  t.plan(2)
  t.equal(account.getAllAddresses().length, 2, 'returns only 2 addresses post-construction')

  // iterate the chains
  f.addresses.forEach(function (a, i) {
    for (let j = 1; j < a.length; ++j) account.nextChainAddress(i)
  })

  t.same(account.getAllAddresses(), f.allAddresses, 'returns all derived addresses')
})

test('getChainAddress', function (t) {
  const account = blankAccount(f.neutered.json)

  f.addresses.forEach(function (addresses, i) {
    addresses.forEach(function (address) {
      t.equal(account.getChainAddress(i), address, 'matches the latest chain address')
      account.nextChainAddress(i)
    })
  })

  t.end()
})

test('getNetwork', function (t) {
  const account = Account.fromJSON(f.neutered.json)

  t.plan(1)
  t.equal(account.getNetwork(), account.chains[0].__parent.network, 'matches keyPair network')
})

test('isChainAddress', function (t) {
  const account = Account.fromJSON(f.neutered.json)

  f.addresses.forEach(function (addresses, i) {
    addresses.forEach(function (address) {
      t.equal(account.isChainAddress(i, address), true, 'for same chain')
      t.equal(account.isChainAddress(i === 1 ? 0 : 1, address), false, 'for different chains')
    })
  })

  t.end()
})

test('nextChainAddress', function (t) {
  const account = blankAccount(f.neutered.json)

  // returns the new address
  f.addresses.forEach(function (addresses, i) {
    // skip the first address
    addresses.slice(1).forEach(function (address, j) {
      t.equal(account.getChainAddress(i), addresses[j], 'is moving forward the chain')
      t.equal(account.nextChainAddress(i), address, 'returns the next address: ' + address)
    })
  })

  t.end()
})

test('getChain', function (t) {
  const account = blankAccount(f.neutered.json)

  f.neutered.json.forEach(function (_, i) {
    t.equal(typeof account.getChain(i), 'object')
    t.equal(account.getChain(i), account.chains[i], 'matches internal .chain')
  })

  t.end()
})

test('getChains', function (t) {
  const account = blankAccount(f.neutered.json)

  t.plan(2)
  t.equal(account.getChains().length, f.neutered.json.length, 'returns the expected number of chains')
  t.equal(account.getChains(), account.chains, 'matches internal .chains')
})

test('derive', function (t) {
  const neutered = Account.fromJSON(f.neutered.json)

  t.test('neutered node', function (t) {
    f.addresses.forEach(function (addresses, i) {
      addresses.forEach(function (address, j) {
        const actual = neutered.derive(address)
        const expected = f.neutered.children[i][j]

        t.equal(expected, actual.toBase58(), 'return a neutered node')
      })
    })

    const unknown = neutered.derive('mpFZW4A9QtRuSpuh9SmeW7RSzFE3TgB8Ko')
    t.equal(undefined, unknown, 'ignores unknown addresses')
    t.end()
  })

  const priv = Account.fromJSON(f.private.json)

  t.test('neutered node w/ escalation', function (t) {
    const privParents = priv.chains.map(function (x) { return x.__parent })

    f.addresses.forEach(function (addresses, i) {
      addresses.forEach(function (address, j) {
        const actual = neutered.derive(address, privParents)
        const expected = f.private.children[i][j]

        t.equal(expected, actual.toBase58(), 'returns a private node')
      })
    })

    const unknown = neutered.derive('mpFZW4A9QtRuSpuh9SmeW7RSzFE3TgB8Ko')
    t.equal(undefined, unknown, 'ignores unknown addresses')
    t.end()
  })

  t.test('private node', function (t) {
    f.addresses.forEach(function (addresses, i) {
      addresses.forEach(function (address, j) {
        const actual = priv.derive(address)
        const expected = f.private.children[i][j]

        t.equal(expected, actual.toBase58(), 'returns a private node')
      })
    })

    const unknown = neutered.derive('mpFZW4A9QtRuSpuh9SmeW7RSzFE3TgB8Ko')
    t.equal(undefined, unknown, 'ignores unknown addresses')
    t.end()
  })

  t.end()
})

// TODO
test('discoverChain', function (t) {
  // .getChainAddress() should remain the same after a uneventful discovery
  // .getChainAddress() should change after an eventful discovery
  t.end()
})

test('toJSON', function (t) {
  const neutered = Account.fromJSON(f.neutered.json)
  const priv = Account.fromJSON(f.private.json)

  t.plan(2)
  t.same(neutered.toJSON(), f.neutered.json, 'neutered json matches fixtures')
  t.same(priv.toJSON(), f.private.json, 'priv json matches fixtures')
})


text:
package org.globus.gsi;

/**
 * Defines common constants used by GSI.
 */
// COMMENT: 2 ways to defined a certificate type: integer and enum.
public interface GSIConstants {

    /** The character sent on the wire to request delegation */
    public static final char DELEGATION_CHAR = 'D';

    /** Null ciphersuite supported in older Globus servers */
    public static final String[] GLOBUS_CIPHER  = {"SSL_RSA_WITH_NULL_MD5"};

    /** Indicates no delegation
     * @deprecated Use DelegationType.NONE instead
     */
    public static final int DELEGATION_NONE = 1;

    /** Indicates limited delegation.
     * Depending on the settings it might mean GSI-2 limited delegation
     * or GSI-3 limited delegation.
     * @deprecated Use DelegationType.LIMITED instead
     */
    public static final int DELEGATION_LIMITED = 2;

    /** Indicates full delegation.
     * Depending on the settings it might mean GSI-2 full delegation
     * or GSI-3 impersonation delegation.
     * @deprecated Use DelegationType.FULL instead
     */
    public static final int DELEGATION_FULL = 3;

    /** Indicates GSI mode (allows for delegation during authentication).
     */
    public static final Integer MODE_GSI = new Integer(1);

    /** Indicates SSL compatibility mode (does not allow for delegation
     * during authentication). */
    public static final Integer MODE_SSL = new Integer(2);

    /** Indicates full delegation. */
    public static final Integer DELEGATION_TYPE_FULL
    = new Integer(GSIConstants.DELEGATION_FULL);

    /** Indicates limited delegation. */
    public static final Integer DELEGATION_TYPE_LIMITED
    = new Integer(GSIConstants.DELEGATION_LIMITED);

    /** Indicates End-Entity Certificate, e.g. user certificate
     * @deprecated Use CertificateType.EEC instead
     */
    public static final int EEC = 3;

    /** Indicates Certificate Authority certificate
     * @deprecated Use CertificateType.CA instead
     */
    public static final int CA = 4;

    /** Indicates legacy full Globus proxy
     * @deprecated Use CertificateType.GSI_2_PROXY instead
     */
    public static final int GSI_2_PROXY         = 10;

    /** Indicates legacy limited Globus proxy
     * @deprecated Use CertificateType.GSI_2_LIMITED_PROXY instead
     */
    public static final int GSI_2_LIMITED_PROXY = 11;

    /** Indicates proxy draft compliant restricted proxy.
     * A proxy with embedded policy.
     * @deprecated Use CertificateType.GSI_3_RESTRICTED_PROXY instead
     */
    public static final int GSI_3_RESTRICTED_PROXY    = 12;

    /** Indicates proxy draft compliant independent proxy.
     * A proxy with {@link org.globus.gsi.proxy.ext.ProxyPolicy#INDEPENDENT
     * ProxyPolicy.INDEPENDENT} policy language OID.
     * @deprecated Use CertificateType.GSI_3_INDEPENDENT_PROXY instead
     */
    public static final int GSI_3_INDEPENDENT_PROXY   = 13;

    /** Indicates proxy draft compliant impersonation proxy.
     * A proxy with {@link org.globus.gsi.proxy.ext.ProxyPolicy#IMPERSONATION
     * ProxyPolicy.IMPERSONATION} policy language OID.
     * @deprecated Use CertificateType.GSI_3_IMPERSONATION_PROXY instead
     */
    public static final int GSI_3_IMPERSONATION_PROXY = 14;

    /** Indicates proxy draft compliant limited impersonation proxy.
     * A proxy with {@link org.globus.gsi.proxy.ext.ProxyPolicy#LIMITED
     * ProxyPolicy.LIMITED} policy language OID.
     * @deprecated Use CertificateType.GSI_3_RESTRICTED_PROXY instead
     */
    public static final int GSI_3_LIMITED_PROXY       = 15;

    /** Indicates RFC 3820 compliant restricted proxy.
     * A proxy with embedded policy.
     * @deprecated Use CertificateType.GSI_4_RESTRICTED_PROXY instead
     */
    public static final int GSI_4_RESTRICTED_PROXY    = 16;

    /** Indicates RFC 3820 compliant independent proxy.
     * A proxy with {@link org.globus.gsi.proxy.ext.ProxyPolicy#INDEPENDENT
     * ProxyPolicy.INDEPENDENT} policy language OID.
     * @deprecated Use CertificateType.GSI_4_INDEPENDENT_PROXY instead
     */
    public static final int GSI_4_INDEPENDENT_PROXY   = 17;

    /** Indicates RFC 3820 compliant impersonation proxy.
     * A proxy with {@link org.globus.gsi.proxy.ext.ProxyPolicy#IMPERSONATION
     * ProxyPolicy.IMPERSONATION} policy language OID.
     * @deprecated Use CertificateType.GSI_4_IMPERSONATION_PROXY instead
     */
    public static final int GSI_4_IMPERSONATION_PROXY = 18;

    /** Indicates RFC 3820 compliant limited impersonation proxy.
     * A proxy with {@link org.globus.gsi.proxy.ext.ProxyPolicy#LIMITED
     * ProxyPolicy.LIMITED} policy language OID.
     * @deprecated Use CertificateType.GSI_4_LIMITED_PROXY instead
     */
    public static final int GSI_4_LIMITED_PROXY       = 19;

    /** GSI Transport protection method type
     * that will be used or was used to protect the request.
     * Can be set to:
     * {@link GSIConstants#SIGNATURE SIGNATURE} or
     * {@link GSIConstants#ENCRYPTION ENCRYPTION} or
     * {@link GSIConstants#NONE NONE}.
     */
    public static final String GSI_TRANSPORT =
        "org.globus.security.transport.type";

    /** integrity message protection method. */
    public static final Integer SIGNATURE
        = new Integer(1);

    /** privacy message protection method. */
    public static final Integer ENCRYPTION
        = new Integer(2);

    /** none message protection method. */
    public static final Integer NONE =
        new Integer(Integer.MAX_VALUE);

    /**
     * It is used to set a list of trusted certificates
     * to use during authentication (by default, the trusted certificates
     * are loaded from a standard location) The value is an instance of
     * {@link org.globus.gsi.TrustedCertificates TrustedCertificates}
     */
    public static final String TRUSTED_CERTIFICATES =
        "org.globus.security.trustedCertifictes";

    /**
     * It is set to a Boolean value and if false,
     * client authorization requirement with delegation is disabled. By
     * default, client side authorization (to authorize the server) is
     * required for delegation of credentials.
     */
    public static final String AUTHZ_REQUIRED_WITH_DELEGATION =
        "org.globus.security.authz.required.delegation";

    /**
     * Enumeration of Certificate types used by the Globus security provider.
     */
    // COMMENT: TODO: replace the the cert type constants with this enum
    public enum CertificateType {
        EEC(3), CA(4), GSI_2_PROXY(10), GSI_2_LIMITED_PROXY(11), GSI_3_RESTRICTED_PROXY(12),
        GSI_3_INDEPENDENT_PROXY(13), GSI_3_IMPERSONATION_PROXY(14), GSI_3_LIMITED_PROXY(15),
        GSI_4_RESTRICTED_PROXY(16), GSI_4_INDEPENDENT_PROXY(17), GSI_4_IMPERSONATION_PROXY(18),
        GSI_4_LIMITED_PROXY(19), UNDEFINED(-1);

        private int code;

        private CertificateType(int c) {
            code = c;
        }

        public int getCode() {
            return code;
        }

        public static CertificateType get(int code) {
            for (CertificateType tmp : CertificateType.values()) {
                if (tmp.getCode() == code) {
                    return tmp;
                }
            }
            throw new IllegalArgumentException("invalid certificate type code");
        }
    }

    /**
     * Enumeration of Certificate types used by the Globus security provider.
     */
    // COMMENT: TODO: replace the the delegation type constants with this enum
    public enum DelegationType {
        NONE(1), LIMITED(2), FULL(3);

        private int code;

        private DelegationType(int c) {
            code = c;
        }

        public int getCode() {
            return code;
        }

        public static DelegationType get(int code) {
            for (DelegationType tmp : DelegationType.values()) {
                if (tmp.getCode() == code) {
                    return tmp;
                }
            }
            throw new IllegalArgumentException("invalid delegation type code");
        }
    }

}


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Cubanacan\WSBundle\WSClass;

use JMS\Serializer\Annotation\Type;
/**
 * Description of HotelCategoryEnum
 *
 * @author obretau
 */
class HotelCategoryEnum {

    const ZERO_STAR = 0;
    const ONE_STAR = 1;
    const TWO_STAR = 2;
    const THREE_STAR = 3;
    const FOUR_STAR = 4;
    const FIVE_STAR = 5;
}


text:
<?php

namespace Entity;

/**
 * Class UserException
 * @package Entity
 */
class UserException extends \Exception {}

/**
 * Class User
 * @package Entity
 */
class User {
    /**
     * @var integer $id
     */
    protected $id;
    /**
     * @var boolean $admin
     */
    protected $admin;
    /**
     * @var string $email
     */
    protected $email;
    /**
     * @var string $password
     */
    protected $password;
    /**
     * @var string $firstname
     */
    protected $firstname;
    /**
     * @var string $lastname
     */
    protected $lastname;
    /**
     * @var string $address
     */
    protected $address;
    /**
     * @var string $zip
     */
    protected $zip;
    /**
     * @var string $place
     */
    protected $place;
    /**
     * @var Country $country
     */
    protected $country;
    /**
     * @var \Doctrine\Common\Collections\ArrayCollection|Order[] $orders
     */
    protected $orders;

    public function __construct()
    {
        $this->admin = false;
    }

    /**
     * @param string $address
     */
    public function setAddress($address)
    {
        $this->address = $address;
    }

    /**
     * @return string
     */
    public function getAddress()
    {
        return $this->address;
    }

    /**
     * @param boolean $admin
     */
    public function setAdmin($admin)
    {
        $this->admin = $admin;
    }

    /**
     * @return boolean
     */
    public function getAdmin()
    {
        return $this->admin;
    }

    /**
     * @param Country $country
     */
    public function setCountry($country)
    {
        $this->country = $country;
    }

    /**
     * @return Country
     */
    public function getCountry()
    {
        return $this->country;
    }

    /**
     * @param string $email
     */
    public function setEmail($email)
    {
        $this->email = $email;
    }

    /**
     * @return string
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * @param string $firstname
     */
    public function setFirstname($firstname)
    {
        $this->firstname = $firstname;
    }

    /**
     * @return string
     */
    public function getFirstname()
    {
        return $this->firstname;
    }

    /**
     * @param int $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param string $lastname
     */
    public function setLastname($lastname)
    {
        $this->lastname = $lastname;
    }

    /**
     * @return string
     */
    public function getLastname()
    {
        return $this->lastname;
    }

    /**
     * @link http://alias.io/2010/01/store-passwords-safely-with-php-and-mysql/
     * @param string $password
     */
    public function setPassword($password)
    {
        // A higher "cost" is more secure but consumes more processing power
        $cost = 10;

        // Create a random salt
        $salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');

        // Prefix information about the hash so PHP knows how to verify it later.
        // "$2a$" Means we're using the Blowfish algorithm. The following two digits are the cost parameter.
        $salt = sprintf("$2a$%02d$", $cost) . $salt;

        // Hash the password with the salt
        $this->password = crypt($password, $salt);
    }

    /**
     * @return string
     */
    public function getPassword()
    {
        return $this->password;
    }

    /**
     * @param string $place
     */
    public function setPlace($place)
    {
        $this->place = $place;
    }

    /**
     * @return string
     */
    public function getPlace()
    {
        return $this->place;
    }

    /**
     * @param string $zip
     */
    public function setZip($zip)
    {
        $this->zip = $zip;
    }

    /**
     * @return string
     */
    public function getZip()
    {
        return $this->zip;
    }

    /**
     * @param mixed $orders
     */
    public function setOrders($orders)
    {
        $this->orders = $orders;
    }

    /**
     * @return mixed
     */
    public function getOrders()
    {
        return $this->orders;
    }
}


text:
<?php

namespace App\Http\Resources\Twitch;

use Illuminate\Http\Resources\Json\JsonResource;

class Streams extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        $streams = Stream::collection(collect($this->resource['data']));
        $pagination = Pagination::make($this->resource['pagination']);

        return [
            'streams' => $streams->resolve(),
            'pagination' => $pagination->resolve(),
        ];
    }
}


text:
using namespace std;

int main(){
   string nome = "Teste";
   cout << nome.length() << endl;
}

//https://pt.stackoverflow.com/q/513275/101


text:
<?php

namespace WpMvc
{
  class BaseModel
  {
    public static $table_name;
    public static $class_name;
    public static $id_column;
    protected $db_columns;

    public function __construct()
    {
      $this->populate();
    }

    public static function all($get_relations = true, $table_name = "")
    {
      global $wpdb;

      if ($table_name == "")
        $table_name = static::$table_name;

      $class_name = static::$class_name;

      $results = $wpdb->get_results( "SELECT * FROM $table_name;" );

      $all = array();

      foreach ( $results as $result ) {
        $return_object = new $class_name();

        $return_object->populate_fields( $result, $return_object );

        if ( $get_relations ) {
          $return_object->init_class_relations();
        }

        $return_object->source_object = clone $return_object;
        $return_object->__db_table = $table_name;

        array_push( $all, $return_object );
      }

      return $all;
    }

    public static function find_by_name($name, $get_relations = true, $table_name = "")
    {
      global $wpdb;

      if ($table_name == "")
        $table_name = static::$table_name;

      $name_column = static::$name_column;
      $class_name = static::$class_name;

      $results = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $table_name WHERE $name_column = %s LIMIT 1;", $name ) );

      $return_object = new $class_name();

      if ( $results ) {
        $return_object->populate_fields( $results[0], $return_object );
      } else {
        throw new \Exception( "Couldn't find $id_column $id of $class_name in $table_name.", E_USER_ERROR );
      }

      if ( $get_relations ) {
        $return_object->init_class_relations();
      }

      $return_object->source_object = clone $return_object;
      $return_object->__db_table = $table_name;

      return $return_object;
    }

    public static function find($id, $get_relations = true, $table_name = "")
    {
      global $wpdb;

      if ($table_name == "")
        $table_name = static::$table_name;

      $id_column = static::$id_column;
      $class_name = static::$class_name;

      $results = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $table_name WHERE $id_column = %s LIMIT 1;", $id ) );

      $return_object = new $class_name();

      if ( $results ) {
        $return_object->populate_fields( $results[0], $return_object );
      } else {
        return false;
      }

      if ( $get_relations ) {
        $return_object->init_class_relations();
      }

      $return_object->source_object = clone $return_object;
      $return_object->__db_table = $table_name;

      return $return_object;
    }

    public static function query($query, $get_relations = true, $table_name = "")
    {
      global $wpdb;

      if ($table_name == "")
        $table_name = static::$table_name;

      $class_name = static::$class_name;

      $results = $wpdb->get_results( $query );

      $all = array();

      if ( $results ) {
        foreach ( $results as $result ) {
          $return_object = new $class_name();

          $return_object->populate_fields( $result, $return_object );

          if ( $get_relations ) {
            $return_object->init_class_relations();
          }

          $return_object->source_object = clone $return_object;
          $return_object->__db_table = $table_name;

          array_push( $all, $return_object );
        }
      } else {
        return false;
      }

      return $all;
    }

    public static function virgin($table_name = "")
    {
      if ($table_name == "")
        $table_name = static::$table_name;

      $class_name = static::$class_name;

      $return_object = new $class_name();

      $return_object->source_object = clone $return_object;
      $return_object->__db_table = $table_name;

      return $return_object;
    }

    public function takes_post( $post )
    {
      $key_array = array();
      $depth = 0;
      $this->iterate_post_keys_and_populate( $post, $key_array, $depth );
    }

    public function save()
    {
      $object_array = array();

      $this->iterate_object_for_method_save( $this, $object_array );

      foreach ( $object_array as $object ) {
        $object->save();
      }

      if ( isset( $this->delete_action ) ) {
        $this->delete();
      } else {
        $this->validate();

        $this->{static::$id_column} ? $id = $this->update() : $id = $this->create();

        return $id;
      }
    }

    public function delete()
    {
      global $wpdb;

      $table_name = static::$table_name;
      $id_column = static::$id_column;
      $id = $this->{static::$id_column};

      $wpdb->query( $wpdb->prepare( "DELETE FROM $table_name WHERE $id_column = %s", $id ) );

      return $id_column;
    }

    protected function validate()
    {
      if ( method_exists( $this, 'validate_uniqueness' ) )
        $this->validate_uniqueness();
    }

    protected function populate()
    {
      global $wpdb;

      $table_name = static::$table_name;

      $results = $wpdb->get_results( "SHOW COLUMNS FROM $table_name;" );

      $this->db_columns = $results;

      foreach ( $results as $result ) {
        if ( ! property_exists( $this, $result->Field ) ) {
          $this->{$result->Field} = null;
        }
      }
    }

    protected function populate_fields( $result, &$return_object = null )
    {
      foreach ( $result as $field => $value )
        $return_object ? $return_object->{$field} = $value : $this->{$field} = $value;
    }

    private function iterate_post_keys_and_populate( $post, &$key_array, $depth )
    {
      foreach ( $post as $post_key => $post_value ) {
        if( is_array( $post_value ) ) {
          $depth++;

          if ( isset( $post_value['delete_action'] ) ) {
            $post_value['delete_action'] = true;
          }

          array_push( $key_array, $post_key );

          $this->iterate_post_keys_and_populate( $post_value, &$key_array, $depth );

          array_pop( $key_array );
        } else {
          array_push( $key_array, $post_key );

          switch ( count( $key_array ) ) {
            case 0:
              echo "1";
              break;
            case 1:
              echo "2";
              break;
            case 2:
              echo "3";
              break;
            case 3:
              $this->{$key_array[0]}->{$key_array[1]}->{$key_array[2]} = $post_value;
              break;
            case 4:
              $this->{$key_array[0]}->{$key_array[1]}->{$key_array[2]}->{$key_array[3]}  = $post_value;
              break;
            case 4:
              break;
            case 5:
              break;
          }

          array_pop( $key_array );
        }
      }

      $depth = 0;
    }

    private function iterate_object_for_method_save( $object, &$object_array )
    {
      foreach ( $object as $object_item ) {
        if ( is_object( $object_item ) ) {
          if ( method_exists( $object_item, 'save' ) )
            array_push( $object_array, $object_item );

          $this->iterate_object_for_method_save( $object_item, $object_array );
        }
      }
    }

    public function init_class_relations()
    {
      if ( method_exists( $this, 'init_relations' ) )
        $this->init_relations();
    }

    private function create()
    {
      global $wpdb;

      $table_name = static::$table_name;
      if (isset($this->__db_table))
        $table_name = $this->__db_table;

      $result = $wpdb->insert( $table_name, $this->as_db_array() );

      if ($result)
        return $wpdb->insert_id;
      else
        return false;
    }

    private function update()
    {
      global $wpdb;

      $table_name = static::$table_name;
      if (isset($this->__db_table))
        $table_name = $this->__db_table;
      $id_column = static::$id_column;
      $id = $this->{static::$id_column};

      $columns_array = $this->as_db_array();

      if (is_array($columns_array) && count($columns_array) > 0) {
        $result = $wpdb->update(
          $table_name,
          $columns_array,
          array(
            $id_column => $id
          )
        );

        return $id;
      } else {
        return false;
      }
    }

    private function as_db_array()
    {
      $return_array = array();

      foreach ( $this->db_columns as $db_column ) {
        $backtrace = debug_backtrace();

        if ($backtrace[1]["function"] != "create" && !isset($this->source_object->{$db_column->Field})) {
          continue;
        }

        if ($backtrace[1]["function"] != "create" && $this->{$db_column->Field} == $this->source_object->{$db_column->Field}) {
          continue;
        }

        if ($this->{$db_column->Field} || $this->{$db_column->Field} == 0)
          $return_array[$db_column->Field] = $this->{$db_column->Field};
      }

      return $return_array;
    }
  }
}


text:
package com.facebook.buck.cxx;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;

import com.facebook.buck.core.build.buildable.context.FakeBuildableContext;
import com.facebook.buck.core.build.context.BuildContext;
import com.facebook.buck.core.build.context.FakeBuildContext;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.BuildTargetFactory;
import com.facebook.buck.core.model.impl.BuildTargetPaths;
import com.facebook.buck.core.rulekey.RuleKey;
import com.facebook.buck.core.rules.ActionGraphBuilder;
import com.facebook.buck.core.rules.SourcePathRuleFinder;
import com.facebook.buck.core.rules.resolver.impl.TestActionGraphBuilder;
import com.facebook.buck.core.sourcepath.PathSourcePath;
import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.core.sourcepath.resolver.SourcePathResolver;
import com.facebook.buck.core.sourcepath.resolver.impl.DefaultSourcePathResolver;
import com.facebook.buck.io.BuildCellRelativePath;
import com.facebook.buck.io.file.MorePaths;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.io.filesystem.TestProjectFilesystems;
import com.facebook.buck.io.filesystem.impl.FakeProjectFilesystem;
import com.facebook.buck.rules.keys.TestDefaultRuleKeyFactory;
import com.facebook.buck.rules.keys.TestInputBasedRuleKeyFactory;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.fs.MkdirStep;
import com.facebook.buck.step.fs.RmStep;
import com.facebook.buck.testutil.TemporaryPaths;
import com.facebook.buck.util.cache.FileHashCacheMode;
import com.facebook.buck.util.cache.impl.DefaultFileHashCache;
import com.facebook.buck.util.cache.impl.StackedFileHashCache;
import com.facebook.buck.util.hashing.FileHashLoader;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

public class DirectHeaderMapTest {

  @Rule public final TemporaryPaths tmpDir = new TemporaryPaths();

  private ProjectFilesystem projectFilesystem;
  private BuildTarget buildTarget;
  private DirectHeaderMap buildRule;
  private ActionGraphBuilder graphBuilder;
  private SourcePathResolver pathResolver;
  private ImmutableMap<Path, SourcePath> links;
  private Path symlinkTreeRoot;
  private Path headerMapPath;
  private Path file1;
  private Path file2;
  private SourcePathRuleFinder ruleFinder;

  @Before
  public void setUp() throws Exception {
    projectFilesystem = new FakeProjectFilesystem(tmpDir.getRoot());

    // Create a build target to use when building the symlink tree.
    buildTarget = BuildTargetFactory.newInstance("//test:test");

    // Get the first file we're symlinking
    Path link1 = Paths.get("file");
    file1 = tmpDir.newFile();
    Files.write(file1, "hello world".getBytes(Charsets.UTF_8));

    // Get the second file we're symlinking
    Path link2 = Paths.get("directory", "then", "file");
    file2 = tmpDir.newFile();
    Files.write(file2, "hello world".getBytes(Charsets.UTF_8));

    // Setup the map representing the link tree.
    links =
        ImmutableMap.of(
            link1,
            PathSourcePath.of(projectFilesystem, MorePaths.relativize(tmpDir.getRoot(), file1)),
            link2,
            PathSourcePath.of(projectFilesystem, MorePaths.relativize(tmpDir.getRoot(), file2)));

    // The output path used by the buildable for the link tree.
    symlinkTreeRoot =
        BuildTargetPaths.getGenPath(projectFilesystem, buildTarget, "%s/symlink-tree-root");

    // Setup the symlink tree buildable.
    graphBuilder = new TestActionGraphBuilder();

    ruleFinder = new SourcePathRuleFinder(graphBuilder);
    pathResolver = DefaultSourcePathResolver.from(ruleFinder);

    buildRule =
        new DirectHeaderMap(buildTarget, projectFilesystem, symlinkTreeRoot, links, ruleFinder);
    graphBuilder.addToIndex(buildRule);

    headerMapPath = pathResolver.getRelativePath(buildRule.getSourcePathToOutput());
  }

  @Test
  public void testBuildSteps() {
    BuildContext buildContext = FakeBuildContext.withSourcePathResolver(pathResolver);
    FakeBuildableContext buildableContext = new FakeBuildableContext();

    Path includeRoot = projectFilesystem.resolve(buildRule.getIncludeRoot());
    ImmutableList<Step> expectedBuildSteps =
        ImmutableList.of(
            RmStep.of(
                    BuildCellRelativePath.fromCellRelativePath(
                        buildContext.getBuildCellRootPath(),
                        projectFilesystem,
                        buildRule.getRoot()))
                .withRecursive(true),
            MkdirStep.of(
                BuildCellRelativePath.fromCellRelativePath(
                    buildContext.getBuildCellRootPath(), projectFilesystem, buildRule.getRoot())),
            MkdirStep.of(
                BuildCellRelativePath.fromCellRelativePath(
                    buildContext.getBuildCellRootPath(),
                    projectFilesystem,
                    headerMapPath.getParent())),
            RmStep.of(
                BuildCellRelativePath.fromCellRelativePath(
                    buildContext.getBuildCellRootPath(), projectFilesystem, headerMapPath)),
            new HeaderMapStep(
                projectFilesystem,
                headerMapPath,
                ImmutableMap.of(
                    Paths.get("file"), includeRoot.relativize(file1),
                    Paths.get("directory/then/file"), includeRoot.relativize(file2))));
    ImmutableList<Step> actualBuildSteps = buildRule.getBuildSteps(buildContext, buildableContext);
    assertEquals(expectedBuildSteps, actualBuildSteps.subList(1, actualBuildSteps.size()));
  }

  @Test
  public void testSymlinkTreeRuleKeysChangeIfLinkMapChanges() throws Exception {
    Path aFile = tmpDir.newFile();
    Files.write(aFile, "hello world".getBytes(Charsets.UTF_8));
    ImmutableMap.Builder<Path, SourcePath> modifiedLinksBuilder = ImmutableMap.builder();
    for (Path p : links.keySet()) {
      modifiedLinksBuilder.put(tmpDir.getRoot().resolve("modified-" + p), links.get(p));
    }
    DirectHeaderMap modifiedBuildRule =
        new DirectHeaderMap(
            buildTarget,
            projectFilesystem,
            symlinkTreeRoot,
            modifiedLinksBuilder.build(),
            ruleFinder);

    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(new TestActionGraphBuilder());
    SourcePathResolver resolver = DefaultSourcePathResolver.from(ruleFinder);

    // Calculate their rule keys and verify they're different.
    FileHashLoader hashCache =
        new StackedFileHashCache(
            ImmutableList.of(
                DefaultFileHashCache.createDefaultFileHashCache(
                    TestProjectFilesystems.createProjectFilesystem(tmpDir.getRoot()),
                    FileHashCacheMode.DEFAULT)));
    RuleKey key1 = new TestDefaultRuleKeyFactory(hashCache, resolver, ruleFinder).build(buildRule);
    RuleKey key2 =
        new TestDefaultRuleKeyFactory(hashCache, resolver, ruleFinder).build(modifiedBuildRule);
    assertNotEquals(key1, key2);

    key1 = new TestInputBasedRuleKeyFactory(hashCache, resolver, ruleFinder).build(buildRule);
    key2 =
        new TestInputBasedRuleKeyFactory(hashCache, resolver, ruleFinder).build(modifiedBuildRule);
    assertNotEquals(key1, key2);
  }

  @Test
  public void testRuleKeyDoesNotChangeIfLinkTargetsChange()
      throws InterruptedException, IOException {
    ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
    graphBuilder.addToIndex(buildRule);
    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(graphBuilder);
    SourcePathResolver resolver = DefaultSourcePathResolver.from(ruleFinder);
    // Calculate their rule keys and verify they're different.
    DefaultFileHashCache hashCache =
        DefaultFileHashCache.createDefaultFileHashCache(
            TestProjectFilesystems.createProjectFilesystem(tmpDir.getRoot()),
            FileHashCacheMode.DEFAULT);
    FileHashLoader hashLoader = new StackedFileHashCache(ImmutableList.of(hashCache));

    RuleKey defaultKey1 =
        new TestDefaultRuleKeyFactory(hashLoader, resolver, ruleFinder).build(buildRule);
    RuleKey inputKey1 =
        new TestInputBasedRuleKeyFactory(hashLoader, resolver, ruleFinder).build(buildRule);

    Files.write(file1, "hello other world".getBytes());
    hashCache.invalidateAll();

    RuleKey defaultKey2 =
        new TestDefaultRuleKeyFactory(hashLoader, resolver, ruleFinder).build(buildRule);
    RuleKey inputKey2 =
        new TestInputBasedRuleKeyFactory(hashLoader, resolver, ruleFinder).build(buildRule);

    // When the file content changes, the rulekey should change but the input rulekey should be
    // unchanged. This ensures that a dependent's rulekey changes correctly.
    assertNotEquals(defaultKey1, defaultKey2);
    assertEquals(inputKey1, inputKey2);
  }
}


text:
public class SubClassToFreeze : ClassToFreeze
{
    public string Property2 { get; set; }
}


text:
require 'logger'
require 'btcruby'
require 'satoshi-unit'
require 'json'
require 'uri'
require 'open-uri'
require 'yaml'
require 'singleton'
require 'httparty'
require 'faraday'
require 'concurrent'
require_relative 'straight/faraday_monkeypatch'
require_relative 'straight/errors'

module Straight
  class << self
    attr_writer :logger
    def logger
      @logger ||= Logger.new('/dev/null')
    end
  end
end

require_relative 'core_ext/deep_get'

require_relative 'straight/blockchain_adapter'
require_relative 'straight/blockchain_adapters_dispatcher'
require_relative 'straight/blockchain_adapters/blockchain_info_adapter'
require_relative 'straight/blockchain_adapters/biteasy_adapter'
require_relative 'straight/blockchain_adapters/mycelium_adapter'
require_relative 'straight/blockchain_adapters/insight_adapter'
require_relative 'straight/blockchain_adapters/chain_com_adapter'

require_relative 'straight/exchange_rate_adapter'

require_relative 'straight/exchange_rate_adapters/btc_adapter'
require_relative 'straight/exchange_rate_adapters/btc_adapters/bitpay_adapter'
require_relative 'straight/exchange_rate_adapters/btc_adapters/coinbase_adapter'
require_relative 'straight/exchange_rate_adapters/btc_adapters/bitstamp_adapter'
require_relative 'straight/exchange_rate_adapters/btc_adapters/localbitcoins_adapter'
require_relative 'straight/exchange_rate_adapters/btc_adapters/okcoin_adapter'
require_relative 'straight/exchange_rate_adapters/btc_adapters/btce_adapter'
require_relative 'straight/exchange_rate_adapters/btc_adapters/kraken_adapter'
require_relative 'straight/exchange_rate_adapters/btc_adapters/average_rate_adapter'

require_relative 'straight/exchange_rate_adapters/fiat_adapter'
require_relative 'straight/exchange_rate_adapters/fiat_adapters/fixer_adapter'
require_relative 'straight/exchange_rate_adapters/fiat_adapters/yahoo_adapter'

require_relative 'straight/address_providers/bip32'

require_relative 'straight/transaction'
require_relative 'straight/order'
require_relative 'straight/gateway'


text:
define([], function () {
	return 'pretend this is jquery-1.11.1';
});


text:
<!doctype html>

		<meta charset="utf-8">
		<meta name="BRD Chatbot" content="">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<link rel="SHORTCUT ICON" href="http://brd-demo-alexandruraduca264972.codeanyapp.com/demo/favicon.ico" type="image/ico">
		<title>BRD Chatbot Demo</title>

		<link rel="stylesheet" href="../dist/jquery.fbmessenger.css">


text:
import { moduleFor, test } from 'ember-qunit';

moduleFor('controller:event', 'Unit | Controller | event', {
  // Specify the other units that are required for this test.
  // needs: ['controller:foo']
});

// Replace this with your real tests.
test('it exists', function(assert) {
  let controller = this.subject();
  assert.ok(controller);
});


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycotaxon 15: 390 (1982)

#### Original name
Boletus braunii var. brunneoruber Beeli, 1927

### Remarks
null


text:
using System;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;

namespace SOURCE.Domaine
{
    public partial class ActionModeAffichage
    {

        [DataMember]
        public long ID { get; set; }

        [DataMember]
		[StringLength(255)]
        public string Code { get; set; }

        [DataMember]
		[StringLength(255)]
        public string CodeEchange { get; set; }

        [DataMember]
		[StringLength(255)]
        public string Description { get; set; }
    }
}


text:
class ParetoModel: public ProbModel {
protected:
	double min, k;

public:
	ParetoModel(double k, double min):
		min(min), k(k) {}

	inline max_size_t GenRate() {
		return (max_size_t)(min / pow(rand() / (double)(RAND_MAX), 1 / k));
	}
};

#endif


text:
package org.springside.examples.showcase.functional.rest;

import static org.assertj.core.api.Assertions.*;

import org.junit.Test;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;
import org.springside.examples.showcase.functional.BaseFunctionalTestCase;
import org.springside.examples.showcase.webservice.rest.UserDTO;

/**
 * 对基于JAX-RS的实现Restful的测试
 *
 * @author fuyuanwu
 */
public class UserJaxRsFT extends BaseFunctionalTestCase {

	private static String resourceUrl = baseUrl + "/cxf/jaxrs/user";

	private RestTemplate restTemplate = new RestTemplate();

	@Test
	public void getUser() {
		UserDTO user = restTemplate.getForObject(resourceUrl + "/{id}.xml", UserDTO.class, 1L);
		assertThat(user.getLoginName()).isEqualTo("admin");
		assertThat(user.getName()).isEqualTo("管理员");
		assertThat(user.getTeamId()).isEqualTo(1);

		try {
			user = restTemplate.getForObject(resourceUrl + "/{id}.json", UserDTO.class, 1L);
		} catch (HttpStatusCodeException e) {
			fail(e.getMessage());
		}
		assertThat(user.getLoginName()).isEqualTo("admin");
		assertThat(user.getName()).isEqualTo("管理员");
		assertThat(user.getTeamId()).isEqualTo(1);
	}
}