text:
<template is="vr-template" element="vr-football" color="orange">
  <vr-object mixin="sphere" position="-8 -4 -2" rotation="0 45 0" scale=".8 .25 .8" material="color: ${color}"></vr-object>
</template>


text:
file(READ examples/imgui_impl_sdl.cpp IMGUI_IMPL_SDL)
string(REPLACE "#include <SDL" "#include <SDL2/SDL"
    IMGUI_IMPL_SDL "${IMGUI_IMPL_SDL}")
file(WRITE examples/imgui_impl_sdl_patched.cpp "${IMGUI_IMPL_SDL}")

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Net;
using Platform.Collections;
using Platform.VirtualFileSystem.Providers;

namespace Platform.VirtualFileSystem.Network
{
	public class NetworkFileSystemManager
		: AbstractFileSystemManager
	{
		private readonly IPAddress ipAddress;
		private readonly IDictionary<string, IFileSystem> fileSystemCache;

		public NetworkFileSystemManager(IPAddress ipAddress)
		{
			this.ipAddress = ipAddress;
			this.fileSystemCache = new TimedReferenceDictionary<string, IFileSystem>(TimeSpan.FromMinutes(5));
		}

		public override INode Resolve(string uri, NodeType nodeType, AddressScope scope, FileSystemOptions options)
		{
			bool success;
			IFileSystem fileSystem;

			var address = LayeredNodeAddress.Parse(uri);

			lock (this.fileSystemCache)
			{
				success = this.fileSystemCache.TryGetValue(address.RootUri, out fileSystem);
			}

			if (!success)
			{
				var networkUri = String.Format("netvfs://{0}[" + uri + "]/", this.ipAddress);

				fileSystem = FileSystemManager.GetManager().ResolveDirectory(networkUri).FileSystem;

				lock (this.fileSystemCache)
				{
					this.fileSystemCache.Add(address.RootUri, fileSystem);
				}
			}

			return fileSystem.Resolve(address.PathAndQuery);
		}
	}
}


text:
<readable><title>3304712466_18cbdb85fe</title><content>
Bicycle racers being cheered on by some people .
Bicycle road racers passing a group of cheering spectators .
Crowds cheer on cyclists as they complete a race to the finish .
People on bicycles riding through a group of onlookers .
Racers on bikes riding past a crowd .
</content></readable>


text:
try:
    import pytest
    pytest.importorskip('qtpy')
except ImportError:  # pragma: nocover
    pass

from .connect import *   # noqa
from .autoconnect import *  # noqa


text:
package co.tpaga.android.Network;

import java.io.IOException;
import java.net.URI;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class FakeInterceptor implements Interceptor {
    private MockService mockService;

    public FakeInterceptor(MockService mockService) {
        this.mockService = mockService;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Response response = null;

        String responseString;
        // Get Request URI.
        final URI uri = chain.request().url().uri();

        responseString = getResponse(uri);

        response = new Response.Builder()
                .code(mockService.getCodeResponse())
                .message(responseString)
                .request(chain.request())
                .protocol(Protocol.HTTP_1_0)
                .body(ResponseBody.create(MediaType.parse("application/json"), responseString.getBytes()))
                .addHeader("content-type", "application/json")
                .build();
        return response;
    }

    private String getResponse(URI uri) {
        return "{}";
    }
}


text:
const path = require("path");

const chalk = require("chalk");
const { make_debugLog } = require("node-opcua-debug");
const {
    TimestampsToReturn,
    AttributeIds,
    OPCUAClient,
    ClientSubscription,
    ClientMonitoredItem,
    coerceNodeId,
    StatusCodes,
    DataType,
    MonitoringMode
} = require("node-opcua");

const { start_simple_server, crash_simple_server } = require("../../test_helpers/external_server_fixture");

const doDebug = false;
const debugLog = make_debugLog("TEST");
let server_data = null;
const port = 2016;

async function start_external_opcua_server() {
    const options = {
        silent: !doDebug,
        server_sourcefile: path.join(__dirname, "../../test_helpers/bin/simple_server_with_custom_extension_objects.js"),
        port
    };
    server_data = await start_simple_server(options);
}

async function crash_external_opcua_server() {
    await crash_simple_server(server_data);
    server_data= null;
}

// ---------------------------------------------------------------------------------------------------------------------
let client, session, subscription, intervalId, monitoredItem;

async function start_active_client(connectionStrategy) {
    const endpointUrl = server_data.endpointUrl;

    client = OPCUAClient.create({
        connectionStrategy,
        endpointMustExist: false,
        keepSessionAlive: true,
        requestedSessionTimeout: 60000
    });
    client.on("connection_reestablished", ()=> {
        debugLog(chalk.bgWhite.red(" !!!!!!!!!!!!!!!!!!!!!!!!  CONNECTION RE-ESTABLISHED !!!!!!!!!!!!!!!!!!!"));
    });
    client.on("backoff", function (number, delay) {
        debugLog(chalk.bgWhite.yellow("backoff  attempt #"), number, " retrying in ", delay / 1000.0, " seconds");
    });

    const nodeId = coerceNodeId("ns=1;s=MyCounter");

    await client.connect(endpointUrl);

    session = await client.createSession();

    debugLog("session timeout = ", session.timeout);

    session.on("keepalive", function (state) {
        if (doDebug) {
            debugLog(
                chalk.yellow("KeepAlive state="),
                state.toString(),
                " pending request on server = ",
                subscription.publish_engine.nbPendingPublishRequests
            );
        }
    });

    session.on("session_closed", function (statusCode) {
        debugLog(chalk.yellow("Session has closed : statusCode = "), statusCode ? statusCode.toString() : "????");
    });

    // create a subscription
    const parameters = {
        requestedPublishingInterval: 100,
        requestedLifetimeCount: 1000,
        requestedMaxKeepAliveCount: 12,
        maxNotificationsPerPublish: 10,
        publishingEnabled: true,
        priority: 10
    };

    subscription = await session.createSubscription2(parameters);

    subscription
        .on("started", ()=> {/** */})
        .on("internal_error", function (err) {
            debugLog(" received internal error", err.message);
        })
        .on("keepalive", ()=> {
            debugLog(
                chalk.cyan("keepalive "),
                chalk.cyan(" pending request on server = "),
                subscription.publish_engine.nbPendingPublishRequests
            );
        })
        .on("terminated", function (err) {
            debugLog("Session Terminated", err.message);
        });
    if (doDebug) {
        debugLog("started subscription :", subscription.subscriptionId);

        debugLog(" revised parameters ");
        debugLog(
            "  revised maxKeepAliveCount  ",
            subscription.maxKeepAliveCount,
            " ( requested ",
            parameters.requestedMaxKeepAliveCount + ")"
        );
        debugLog(
            "  revised lifetimeCount      ",
            subscription.lifetimeCount,
            " ( requested ",
            parameters.requestedLifetimeCount + ")"
        );
        debugLog(
            "  revised publishingInterval ",
            subscription.publishingInterval,
            " ( requested ",
            parameters.requestedPublishingInterval + ")"
        );
        debugLog("  suggested timeout hint     ", subscription.publish_engine.timeoutHint);
    }

    const result = [];
    const requestedParameters = {
        samplingInterval: 250,
        queueSize: 1,
        discardOldest: true
    };

    const item = { nodeId: nodeId, attributeId: AttributeIds.Value };

    monitoredItem = await subscription.monitor(item, requestedParameters, TimestampsToReturn.Both, MonitoringMode.Reporting);

    monitoredItem.on("changed", function (dataValue) {
        if (doDebug) {
            debugLog(chalk.cyan(" ||||||||||| VALUE CHANGED !!!!"), dataValue.statusCode.toString(), dataValue.value.toString());
        }
        result.push(dataValue);
    });

    let counter = 0;

    function writeValue() {
        if (!intervalId) {
            return;
        }
        if (doDebug) {
            debugLog(
                " Session OK ? ",
                session.isChannelValid(),
                "session will expired in ",
                session.evaluateRemainingLifetime() / 1000,
                " seconds",
                chalk.red("subscription will expire in "),
                subscription.evaluateRemainingLifetime() / 1000,
                " seconds",
                chalk.red("subscription?"),
                session.subscriptionCount
            );
        }
        if (!session.isChannelValid() && false) {
            //xx debugLog(the_session.toString());
            return; // ignore write as session is invalid for the time being
        }

        let nodeToWrite = {
            nodeId: nodeId,
            attributeId: AttributeIds.Value,
            value: /* DataValue */ {
                statusCode: StatusCodes.Good,
                sourceTimestamp: new Date(),
                value: /* Variant */ {
                    dataType: DataType.Int32,
                    value: counter
                }
            }
        };
        session.write(nodeToWrite, function (err, statusCode) {
            if (err) {
                if (doDebug) {
                    debugLog(chalk.red("       writing Failed "), err.message);
                }
            } else {
                if (doDebug) {
                    debugLog("       writing OK counter =", counter, statusCode.toString());
                }
                counter += 1;
            }
            //xx statusCode && statusCode.length===1) ? statusCode[0].toString():"");
            setTimeout(writeValue, 500);
        });
    }
    writeValue();

    await new Promise((resolve) => setTimeout(resolve, 500));
}

async function terminate_active_client() {
    if (!client) {
        return;
    }
    if (intervalId) {
        clearInterval(intervalId);
        intervalId = null;
    }
    if (session) {
        await session.close();
    }
    await client.disconnect();
    client = null;
}

async function f(func) {
    return async ()=> {
        debugLog(
            "       * " +
                func.name
                    .replace(
                        /_/g,

                        " "
                    )
                    .replace(/(given|when|then)/, chalk.green("**$1**"))
        );
        return await func();
    };
}

// eslint-disable-next-line import/order
const describe = require("node-opcua-leak-detector").describeWithLeakDetector;
describe("Testing client reconnection with crashing server", function () {
    this.timeout(100000);

    afterEach(async () => {
        debugLog("------------------------- Terminating client ----------------------------");
        await terminate_active_client();
        await crash_external_opcua_server();
    });

    async function given_a_running_opcua_server() {
        await start_external_opcua_server();
    }

    async function when_the_server_crash() {
        await crash_external_opcua_server();
    }

    async function when_the_server_restart() {
        await start_external_opcua_server();
    }

    async function when_the_server_restart_after_some_very_long_time() {
        await new Promise((resolve) => setTimeout(resolve, 10000));
        await when_the_server_restart();
    }

    async function given_a_active_client_with_subscription_and_monitored_items() {
        // this client starts with default parameters
        await start_active_client(undefined);
    }

    async function given_a_active_client_with_subscription_and_monitored_items_AND_short_retry_strategy() {
        // this client starts with fail fast connection strategy
        await start_active_client({ maxRetry: 2, initialDelay: 100, maxDelay: 200 });
    }

    async function then_client_should_detect_failure_and_enter_reconnection_mode() {
        await new Promise((resolve) => {
            let backoff_counter = 0;

            function backoff_detector() {
                backoff_counter += 1;
                if (backoff_counter === 2) {
                    if (doDebug) {
                        debugLog("Bingo !  Client has detected disconnection and is currently trying to reconnect");
                    }
                    client.removeListener("backoff", backoff_detector);
                    resolve();
                }
            }

            client.on("backoff", backoff_detector);
        });
    }

    async function then_client_should_reconnect_and_restore_subscription() {
        await new Promise((resolve) => {
            let change_counter = 0;
            function on_value_changed(dataValue) {
                change_counter += 1;
                if (doDebug) {
                    debugLog(" |||||||||||||||||||| DataValue changed again !!!", dataValue.toString());
                }
                if (change_counter === 3) {
                    monitoredItem.removeListener("value_changed", on_value_changed);
                    resolve();
                }
            }
            monitoredItem.on("changed", on_value_changed);
        });
    }

    it("should reconnection and restore subscriptions when server becomes available again", async () => {
        await f(given_a_running_opcua_server);
        await f(given_a_active_client_with_subscription_and_monitored_items);
        await f(when_the_server_crash);
        await f(then_client_should_detect_failure_and_enter_reconnection_mode);
        await f(when_the_server_restart);
        await f(then_client_should_reconnect_and_restore_subscription);
    });
    it("testing reconnection with failFastReconnection strategy #606", async () => {
        // rationale:
        //  even if the OPCUAClient  uses a fail fast reconnection strategy, a lost of connection
        //  should cause an infinite retry to connect again
        await f(given_a_running_opcua_server);
        await f(given_a_active_client_with_subscription_and_monitored_items_AND_short_retry_strategy);
        await f(when_the_server_crash);
        await f(then_client_should_detect_failure_and_enter_reconnection_mode);
        await f(when_the_server_restart_after_some_very_long_time);
        await f(then_client_should_reconnect_and_restore_subscription);
    });
});


text:
package org.wso2.carbon.device.mgt.jaxrs.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataService;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.InputValidationException;
import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
import org.wso2.carbon.identity.user.store.count.AbstractCountRetrieverFactory;
import org.wso2.carbon.identity.user.store.count.UserStoreCountRetriever;
import org.wso2.carbon.identity.user.store.count.exception.UserStoreCounterException;
import org.wso2.carbon.identity.user.store.count.jdbc.JDBCCountRetrieverFactory;
import org.wso2.carbon.identity.user.store.count.jdbc.internal.InternalCountRetrieverFactory;
import org.wso2.carbon.policy.mgt.common.PolicyMonitoringTaskException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.api.AuthorizationManager;
import org.wso2.carbon.user.api.RealmConfiguration;
import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager;
import org.wso2.carbon.user.core.service.RealmService;

import javax.ws.rs.core.MediaType;
import java.util.List;

/**
 * MDMAPIUtils class provides utility function used by CDM REST-API classes.
 */
public class DeviceMgtAPIUtils {

    public static final MediaType DEFAULT_CONTENT_TYPE = MediaType.APPLICATION_JSON_TYPE;
    private static final String NOTIFIER_FREQUENCY = "notifierFrequency";
    private static Log log = LogFactory.getLog(DeviceMgtAPIUtils.class);

    public static int getNotifierFrequency(PlatformConfiguration tenantConfiguration) {
        List<ConfigurationEntry> configEntryList = tenantConfiguration.getConfiguration();
        if (configEntryList != null && !configEntryList.isEmpty()) {
            for (ConfigurationEntry entry : configEntryList) {
                if (NOTIFIER_FREQUENCY.equals(entry.getName())) {
                    if (entry.getValue() == null) {
                        throw new InputValidationException(
                                new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(
                                        "Notifier frequency cannot be null. Please specify a valid non-negative " +
                                                "integer value to successfully set up notification frequency. " +
                                                "Should the service be stopped, use '0' as the notification " +
                                                "frequency.").build()
                        );
                    }
                    return (int) (Double.parseDouble(entry.getValue().toString()) + 0.5d);
                }
            }
        }
        return 0;
    }

    public static void scheduleTaskService(int notifierFrequency) {
        TaskScheduleService taskScheduleService;
        try {
            taskScheduleService = getPolicyManagementService().getTaskScheduleService();
            if (taskScheduleService.isTaskScheduled()) {
                taskScheduleService.updateTask(notifierFrequency);
            } else {
                taskScheduleService.startTask(notifierFrequency);
            }
        } catch (PolicyMonitoringTaskException e) {
            log.error("Exception occurred while starting the Task service.", e);
        }
    }

    public static DeviceManagementProviderService getDeviceManagementService() {
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        DeviceManagementProviderService deviceManagementProviderService =
                (DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null);
        if (deviceManagementProviderService == null) {
            String msg = "DeviceImpl Management provider service has not initialized.";
            log.error(msg);
            throw new IllegalStateException(msg);
        }
        return deviceManagementProviderService;
    }

    public static UserStoreCountRetriever getUserStoreCountRetrieverService()
            throws UserStoreCounterException {
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        List<Object> countRetrieverFactories = ctx.getOSGiServices(AbstractCountRetrieverFactory.class, null);
        RealmService realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);
        RealmConfiguration realmConfiguration = realmService.getBootstrapRealmConfiguration();
        String userStoreType;
        //Ignoring Sonar warning as getUserStoreClass() returning string name of the class. So cannot use 'instanceof'.
        if (JDBCUserStoreManager.class.getName().equals(realmConfiguration.getUserStoreClass())) {
            userStoreType = JDBCCountRetrieverFactory.JDBC;
        } else {
            userStoreType = InternalCountRetrieverFactory.INTERNAL;
        }
        AbstractCountRetrieverFactory countRetrieverFactory = null;
        for (Object countRetrieverFactoryObj : countRetrieverFactories) {
            countRetrieverFactory = (AbstractCountRetrieverFactory) countRetrieverFactoryObj;
            if (userStoreType.equals(countRetrieverFactory.getCounterType())) {
                break;
            }
        }
        if (countRetrieverFactory == null) {
            return null;
        }
        return countRetrieverFactory.buildCountRetriever(realmConfiguration);
    }

    public static DeviceAccessAuthorizationService getDeviceAccessAuthorizationService() {
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        DeviceAccessAuthorizationService deviceAccessAuthorizationService =
                (DeviceAccessAuthorizationService) ctx.getOSGiService(DeviceAccessAuthorizationService.class, null);
        if (deviceAccessAuthorizationService == null) {
            String msg = "DeviceAccessAuthorization service has not initialized.";
            log.error(msg);
            throw new IllegalStateException(msg);
        }
        return deviceAccessAuthorizationService;
    }

    public static GroupManagementProviderService getGroupManagementProviderService() {
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        GroupManagementProviderService groupManagementProviderService =
                (GroupManagementProviderService) ctx.getOSGiService(GroupManagementProviderService.class, null);
        if (groupManagementProviderService == null) {
            String msg = "GroupImpl Management service has not initialized.";
            log.error(msg);
            throw new IllegalStateException(msg);
        }
        return groupManagementProviderService;
    }

    public static UserStoreManager getUserStoreManager() throws UserStoreException {
        RealmService realmService;
        UserStoreManager userStoreManager;
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);
        if (realmService == null) {
            String msg = "Realm service has not initialized.";
            log.error(msg);
            throw new IllegalStateException(msg);
        }
        int tenantId = ctx.getTenantId();
        userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
        return userStoreManager;
    }

    public static RealmService getRealmService() throws UserStoreException {
        RealmService realmService;
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);
        if (realmService == null) {
            String msg = "Realm service has not initialized.";
            log.error(msg);
            throw new IllegalStateException(msg);
        }
        return realmService;
    }

    public static RegistryService getRegistryService() {
        RegistryService registryService;
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        registryService = (RegistryService) ctx.getOSGiService(RegistryService.class, null);
        if (registryService == null) {
            String msg = "registry service has not initialized.";
            log.error(msg);
            throw new IllegalStateException(msg);
        }
        return registryService;
    }

    public static JWTClientManagerService getJWTClientManagerService() {
        JWTClientManagerService jwtClientManagerService;
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        jwtClientManagerService = (JWTClientManagerService) ctx.getOSGiService(JWTClientManagerService.class, null);
        if (jwtClientManagerService == null) {
            String msg = "jwtClientManagerServicehas not initialized.";
            log.error(msg);
            throw new IllegalStateException(msg);
        }
        return jwtClientManagerService;
    }

    /**
     * Getting the current tenant's user realm
     */
    public static UserRealm getUserRealm() throws UserStoreException {
        RealmService realmService;
        UserRealm realm;
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);

        if (realmService == null) {
            throw new IllegalStateException("Realm service not initialized");
        }
        int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
        realm = realmService.getTenantUserRealm(tenantId);
        return realm;
    }

    public static AuthorizationManager getAuthorizationManager() throws UserStoreException {
        RealmService realmService;
        AuthorizationManager authorizationManager;
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);
        if (realmService == null) {
            throw new IllegalStateException("Realm service is not initialized.");
        }
        int tenantId = ctx.getTenantId();
        authorizationManager = realmService.getTenantUserRealm(tenantId).getAuthorizationManager();

        return authorizationManager;
    }

    public static ApplicationManagementProviderService getAppManagementService() {
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        ApplicationManagementProviderService applicationManagementProviderService =
                (ApplicationManagementProviderService) ctx.getOSGiService(ApplicationManagementProviderService.class, null);
        if (applicationManagementProviderService == null) {
            throw new IllegalStateException("AuthenticationImpl management service has not initialized.");
        }
        return applicationManagementProviderService;
    }

    public static PolicyManagerService getPolicyManagementService() {
        PolicyManagerService policyManagementService;
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        policyManagementService =
                (PolicyManagerService) ctx.getOSGiService(PolicyManagerService.class, null);
        if (policyManagementService == null) {
            String msg = "PolicyImpl Management service not initialized.";
            log.error(msg);
            throw new IllegalStateException(msg);
        }
        return policyManagementService;
    }

    public static PlatformConfigurationManagementService getPlatformConfigurationManagementService() {
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        PlatformConfigurationManagementService tenantConfigurationManagementService =
                (PlatformConfigurationManagementService) ctx.getOSGiService(
                        PlatformConfigurationManagementService.class, null);
        if (tenantConfigurationManagementService == null) {
            throw new IllegalStateException("Tenant configuration Management service not initialized.");
        }
        return tenantConfigurationManagementService;
    }

    public static NotificationManagementService getNotificationManagementService() {
        NotificationManagementService notificationManagementService;
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        notificationManagementService = (NotificationManagementService) ctx.getOSGiService(
                NotificationManagementService.class, null);
        if (notificationManagementService == null) {
            throw new IllegalStateException("Notification Management service not initialized.");
        }
        return notificationManagementService;
    }

    public static DeviceInformationManager getDeviceInformationManagerService() {
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        DeviceInformationManager deviceInformationManager =
                (DeviceInformationManager) ctx.getOSGiService(DeviceInformationManager.class, null);
        if (deviceInformationManager == null) {
            throw new IllegalStateException("DeviceImpl information Manager service has not initialized.");
        }
        return deviceInformationManager;
    }

    public static SearchManagerService getSearchManagerService() {
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        SearchManagerService searchManagerService =
                (SearchManagerService) ctx.getOSGiService(SearchManagerService.class, null);
        if (searchManagerService == null) {
            throw new IllegalStateException("DeviceImpl search manager service is not initialized.");
        }
        return searchManagerService;
    }

    public static GadgetDataService getGadgetDataService() {
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        GadgetDataService gadgetDataService = (GadgetDataService) ctx.getOSGiService(GadgetDataService.class, null);
        if (gadgetDataService == null) {
            throw new IllegalStateException("Gadget Data Service has not been initialized.");
        }
        return gadgetDataService;
    }

    public static int getTenantId(String tenantDomain) throws DeviceManagementException {
        RealmService realmService =
                (RealmService) PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService(RealmService.class, null);
        if (realmService == null) {
            throw new IllegalStateException("Realm service has not been initialized.");
        }
        try {
            return realmService.getTenantManager().getTenantId(tenantDomain);
        } catch (UserStoreException e) {
            throw new DeviceManagementException("Error occured while trying to " +
                "obtain tenant id of currently logged in user");
        }
    }

    public static String getAuthenticatedUser() {
        PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        String username = threadLocalCarbonContext.getUsername();
        String tenantDomain = threadLocalCarbonContext.getTenantDomain();
        if (username != null && username.endsWith(tenantDomain)) {
            return username.substring(0, username.lastIndexOf("@"));
        }
        return username;
    }

}


text:
#define _FILE_OFFSET_BITS 64
#include "radeon_drm_cs.h"

#include "util/u_hash_table.h"
#include "util/u_memory.h"
#include "util/u_simple_list.h"
#include "util/u_double_list.h"
#include "os/os_thread.h"
#include "os/os_mman.h"
#include "os/os_time.h"

#include "state_tracker/drm_driver.h"

#include <sys/ioctl.h>
#include <xf86drm.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>

extern const struct pb_vtbl radeon_bo_vtbl;

static INLINE struct radeon_bo *radeon_bo(struct pb_buffer *bo)
{
    assert(bo->vtbl == &radeon_bo_vtbl);
    return (struct radeon_bo *)bo;
}

struct radeon_bo_va_hole {
    struct list_head list;
    uint64_t         offset;
    uint64_t         size;
};

struct radeon_bomgr {
    /* Base class. */
    struct pb_manager base;

    /* Winsys. */
    struct radeon_drm_winsys *rws;

    /* List of buffer GEM names. Protected by bo_handles_mutex. */
    struct util_hash_table *bo_names;
    /* List of buffer handles. Protectded by bo_handles_mutex. */
    struct util_hash_table *bo_handles;
    /* List of buffer virtual memory ranges. Protectded by bo_handles_mutex. */
    struct util_hash_table *bo_vas;
    pipe_mutex bo_handles_mutex;
    pipe_mutex bo_va_mutex;

    /* is virtual address supported */
    bool va;
    uint64_t va_offset;
    struct list_head va_holes;
};

static INLINE struct radeon_bomgr *radeon_bomgr(struct pb_manager *mgr)
{
    return (struct radeon_bomgr *)mgr;
}

static struct radeon_bo *get_radeon_bo(struct pb_buffer *_buf)
{
    struct radeon_bo *bo = NULL;

    if (_buf->vtbl == &radeon_bo_vtbl) {
        bo = radeon_bo(_buf);
    } else {
        struct pb_buffer *base_buf;
        pb_size offset;
        pb_get_base_buffer(_buf, &base_buf, &offset);

        if (base_buf->vtbl == &radeon_bo_vtbl)
            bo = radeon_bo(base_buf);
    }

    return bo;
}

static void radeon_bo_wait(struct pb_buffer *_buf, enum radeon_bo_usage usage)
{
    struct radeon_bo *bo = get_radeon_bo(_buf);
    struct drm_radeon_gem_wait_idle args = {0};

    while (p_atomic_read(&bo->num_active_ioctls)) {
        sched_yield();
    }

    args.handle = bo->handle;
    while (drmCommandWrite(bo->rws->fd, DRM_RADEON_GEM_WAIT_IDLE,
                           &args, sizeof(args)) == -EBUSY);
}

static boolean radeon_bo_is_busy(struct pb_buffer *_buf,
                                 enum radeon_bo_usage usage)
{
    struct radeon_bo *bo = get_radeon_bo(_buf);
    struct drm_radeon_gem_busy args = {0};

    if (p_atomic_read(&bo->num_active_ioctls)) {
        return TRUE;
    }

    args.handle = bo->handle;
    return drmCommandWriteRead(bo->rws->fd, DRM_RADEON_GEM_BUSY,
                               &args, sizeof(args)) != 0;
}

static enum radeon_bo_domain get_valid_domain(enum radeon_bo_domain domain)
{
    /* Zero domains the driver doesn't understand. */
    domain &= RADEON_DOMAIN_VRAM_GTT;

    /* If no domain is set, we must set something... */
    if (!domain)
        domain = RADEON_DOMAIN_VRAM_GTT;

    return domain;
}

static enum radeon_bo_domain radeon_bo_get_initial_domain(
		struct radeon_winsys_cs_handle *buf)
{
    struct radeon_bo *bo = (struct radeon_bo*)buf;
    struct drm_radeon_gem_op args;

    if (bo->rws->info.drm_minor < 38)
        return RADEON_DOMAIN_VRAM_GTT;

    memset(&args, 0, sizeof(args));
    args.handle = bo->handle;
    args.op = RADEON_GEM_OP_GET_INITIAL_DOMAIN;

    drmCommandWriteRead(bo->rws->fd, DRM_RADEON_GEM_OP,
                        &args, sizeof(args));

    /* GEM domains and winsys domains are defined the same. */
    return get_valid_domain(args.value);
}

static uint64_t radeon_bomgr_find_va(struct radeon_bomgr *mgr, uint64_t size, uint64_t alignment)
{
    struct radeon_bo_va_hole *hole, *n;
    uint64_t offset = 0, waste = 0;

    alignment = MAX2(alignment, 4096);
    size = align(size, 4096);

    pipe_mutex_lock(mgr->bo_va_mutex);
    /* first look for a hole */
    LIST_FOR_EACH_ENTRY_SAFE(hole, n, &mgr->va_holes, list) {
        offset = hole->offset;
        waste = offset % alignment;
        waste = waste ? alignment - waste : 0;
        offset += waste;
        if (offset >= (hole->offset + hole->size)) {
            continue;
        }
        if (!waste && hole->size == size) {
            offset = hole->offset;
            list_del(&hole->list);
            FREE(hole);
            pipe_mutex_unlock(mgr->bo_va_mutex);
            return offset;
        }
        if ((hole->size - waste) > size) {
            if (waste) {
                n = CALLOC_STRUCT(radeon_bo_va_hole);
                n->size = waste;
                n->offset = hole->offset;
                list_add(&n->list, &hole->list);
            }
            hole->size -= (size + waste);
            hole->offset += size + waste;
            pipe_mutex_unlock(mgr->bo_va_mutex);
            return offset;
        }
        if ((hole->size - waste) == size) {
            hole->size = waste;
            pipe_mutex_unlock(mgr->bo_va_mutex);
            return offset;
        }
    }

    offset = mgr->va_offset;
    waste = offset % alignment;
    waste = waste ? alignment - waste : 0;
    if (waste) {
        n = CALLOC_STRUCT(radeon_bo_va_hole);
        n->size = waste;
        n->offset = offset;
        list_add(&n->list, &mgr->va_holes);
    }
    offset += waste;
    mgr->va_offset += size + waste;
    pipe_mutex_unlock(mgr->bo_va_mutex);
    return offset;
}

static void radeon_bomgr_free_va(struct radeon_bomgr *mgr, uint64_t va, uint64_t size)
{
    struct radeon_bo_va_hole *hole;

    size = align(size, 4096);

    pipe_mutex_lock(mgr->bo_va_mutex);
    if ((va + size) == mgr->va_offset) {
        mgr->va_offset = va;
        /* Delete uppermost hole if it reaches the new top */
        if (!LIST_IS_EMPTY(&mgr->va_holes)) {
            hole = container_of(mgr->va_holes.next, hole, list);
            if ((hole->offset + hole->size) == va) {
                mgr->va_offset = hole->offset;
                list_del(&hole->list);
                FREE(hole);
            }
        }
    } else {
        struct radeon_bo_va_hole *next;

        hole = container_of(&mgr->va_holes, hole, list);
        LIST_FOR_EACH_ENTRY(next, &mgr->va_holes, list) {
	    if (next->offset < va)
	        break;
            hole = next;
        }

        if (&hole->list != &mgr->va_holes) {
            /* Grow upper hole if it's adjacent */
            if (hole->offset == (va + size)) {
                hole->offset = va;
                hole->size += size;
                /* Merge lower hole if it's adjacent */
                if (next != hole && &next->list != &mgr->va_holes &&
                    (next->offset + next->size) == va) {
                    next->size += hole->size;
                    list_del(&hole->list);
                    FREE(hole);
                }
                goto out;
            }
        }

        /* Grow lower hole if it's adjacent */
        if (next != hole && &next->list != &mgr->va_holes &&
            (next->offset + next->size) == va) {
            next->size += size;
            goto out;
        }

        /* FIXME on allocation failure we just lose virtual address space
         * maybe print a warning
         */
        next = CALLOC_STRUCT(radeon_bo_va_hole);
        if (next) {
            next->size = size;
            next->offset = va;
            list_add(&next->list, &hole->list);
        }
    }
out:
    pipe_mutex_unlock(mgr->bo_va_mutex);
}

static void radeon_bo_destroy(struct pb_buffer *_buf)
{
    struct radeon_bo *bo = radeon_bo(_buf);
    struct radeon_bomgr *mgr = bo->mgr;
    struct drm_gem_close args;

    memset(&args, 0, sizeof(args));

    pipe_mutex_lock(bo->mgr->bo_handles_mutex);
    util_hash_table_remove(bo->mgr->bo_handles, (void*)(uintptr_t)bo->handle);
    if (bo->flink_name) {
        util_hash_table_remove(bo->mgr->bo_names,
                               (void*)(uintptr_t)bo->flink_name);
    }
    pipe_mutex_unlock(bo->mgr->bo_handles_mutex);

    if (bo->ptr)
        os_munmap(bo->ptr, bo->base.size);

    /* Close object. */
    args.handle = bo->handle;
    drmIoctl(bo->rws->fd, DRM_IOCTL_GEM_CLOSE, &args);

    if (mgr->va) {
        radeon_bomgr_free_va(mgr, bo->va, bo->base.size);
    }

    pipe_mutex_destroy(bo->map_mutex);

    if (bo->initial_domain & RADEON_DOMAIN_VRAM)
        bo->rws->allocated_vram -= align(bo->base.size, 4096);
    else if (bo->initial_domain & RADEON_DOMAIN_GTT)
        bo->rws->allocated_gtt -= align(bo->base.size, 4096);
    FREE(bo);
}

void *radeon_bo_do_map(struct radeon_bo *bo)
{
    struct drm_radeon_gem_mmap args = {0};
    void *ptr;

    /* Return the pointer if it's already mapped. */
    if (bo->ptr)
        return bo->ptr;

    /* Map the buffer. */
    pipe_mutex_lock(bo->map_mutex);
    /* Return the pointer if it's already mapped (in case of a race). */
    if (bo->ptr) {
        pipe_mutex_unlock(bo->map_mutex);
        return bo->ptr;
    }
    args.handle = bo->handle;
    args.offset = 0;
    args.size = (uint64_t)bo->base.size;
    if (drmCommandWriteRead(bo->rws->fd,
                            DRM_RADEON_GEM_MMAP,
                            &args,
                            sizeof(args))) {
        pipe_mutex_unlock(bo->map_mutex);
        fprintf(stderr, "radeon: gem_mmap failed: %p 0x%08X\n",
                bo, bo->handle);
        return NULL;
    }

    ptr = os_mmap(0, args.size, PROT_READ|PROT_WRITE, MAP_SHARED,
               bo->rws->fd, args.addr_ptr);
    if (ptr == MAP_FAILED) {
        pipe_mutex_unlock(bo->map_mutex);
        fprintf(stderr, "radeon: mmap failed, errno: %i\n", errno);
        return NULL;
    }
    bo->ptr = ptr;
    pipe_mutex_unlock(bo->map_mutex);

    return bo->ptr;
}

static void *radeon_bo_map(struct radeon_winsys_cs_handle *buf,
                           struct radeon_winsys_cs *rcs,
                           enum pipe_transfer_usage usage)
{
    struct radeon_bo *bo = (struct radeon_bo*)buf;
    struct radeon_drm_cs *cs = (struct radeon_drm_cs*)rcs;

    /* If it's not unsynchronized bo_map, flush CS if needed and then wait. */
    if (!(usage & PIPE_TRANSFER_UNSYNCHRONIZED)) {
        /* DONTBLOCK doesn't make sense with UNSYNCHRONIZED. */
        if (usage & PIPE_TRANSFER_DONTBLOCK) {
            if (!(usage & PIPE_TRANSFER_WRITE)) {
                /* Mapping for read.
                 *
                 * Since we are mapping for read, we don't need to wait
                 * if the GPU is using the buffer for read too
                 * (neither one is changing it).
                 *
                 * Only check whether the buffer is being used for write. */
                if (cs && radeon_bo_is_referenced_by_cs_for_write(cs, bo)) {
                    cs->flush_cs(cs->flush_data, RADEON_FLUSH_ASYNC, NULL);
                    return NULL;
                }

                if (radeon_bo_is_busy((struct pb_buffer*)bo,
                                      RADEON_USAGE_WRITE)) {
                    return NULL;
                }
            } else {
                if (cs && radeon_bo_is_referenced_by_cs(cs, bo)) {
                    cs->flush_cs(cs->flush_data, RADEON_FLUSH_ASYNC, NULL);
                    return NULL;
                }

                if (radeon_bo_is_busy((struct pb_buffer*)bo,
                                      RADEON_USAGE_READWRITE)) {
                    return NULL;
                }
            }
        } else {
            uint64_t time = os_time_get_nano();

            if (!(usage & PIPE_TRANSFER_WRITE)) {
                /* Mapping for read.
                 *
                 * Since we are mapping for read, we don't need to wait
                 * if the GPU is using the buffer for read too
                 * (neither one is changing it).
                 *
                 * Only check whether the buffer is being used for write. */
                if (cs && radeon_bo_is_referenced_by_cs_for_write(cs, bo)) {
                    cs->flush_cs(cs->flush_data, 0, NULL);
                }
                radeon_bo_wait((struct pb_buffer*)bo,
                               RADEON_USAGE_WRITE);
            } else {
                /* Mapping for write. */
                if (cs) {
                    if (radeon_bo_is_referenced_by_cs(cs, bo)) {
                        cs->flush_cs(cs->flush_data, 0, NULL);
                    } else {
                        /* Try to avoid busy-waiting in radeon_bo_wait. */
                        if (p_atomic_read(&bo->num_active_ioctls))
                            radeon_drm_cs_sync_flush(rcs);
                    }
                }

                radeon_bo_wait((struct pb_buffer*)bo, RADEON_USAGE_READWRITE);
            }

            bo->mgr->rws->buffer_wait_time += os_time_get_nano() - time;
        }
    }

    return radeon_bo_do_map(bo);
}

static void radeon_bo_unmap(struct radeon_winsys_cs_handle *_buf)
{
    /* NOP */
}

static void radeon_bo_get_base_buffer(struct pb_buffer *buf,
                                      struct pb_buffer **base_buf,
                                      unsigned *offset)
{
    *base_buf = buf;
    *offset = 0;
}

static enum pipe_error radeon_bo_validate(struct pb_buffer *_buf,
                                          struct pb_validate *vl,
                                          unsigned flags)
{
    /* Always pinned */
    return PIPE_OK;
}

static void radeon_bo_fence(struct pb_buffer *buf,
                            struct pipe_fence_handle *fence)
{
}

const struct pb_vtbl radeon_bo_vtbl = {
    radeon_bo_destroy,
    NULL, /* never called */
    NULL, /* never called */
    radeon_bo_validate,
    radeon_bo_fence,
    radeon_bo_get_base_buffer,
};

#ifndef RADEON_GEM_GTT_WC
#define RADEON_GEM_GTT_WC (1 << 2)
#endif

static struct pb_buffer *radeon_bomgr_create_bo(struct pb_manager *_mgr,
                                                pb_size size,
                                                const struct pb_desc *desc)
{
    struct radeon_bomgr *mgr = radeon_bomgr(_mgr);
    struct radeon_drm_winsys *rws = mgr->rws;
    struct radeon_bo *bo;
    struct drm_radeon_gem_create args;
    struct radeon_bo_desc *rdesc = (struct radeon_bo_desc*)desc;
    int r;

    memset(&args, 0, sizeof(args));

    assert(rdesc->initial_domains);
    assert((rdesc->initial_domains &
            ~(RADEON_GEM_DOMAIN_GTT | RADEON_GEM_DOMAIN_VRAM)) == 0);

    args.size = size;
    args.alignment = desc->alignment;
    args.initial_domain = rdesc->initial_domains;
    args.flags = 0;

    if (rdesc->flags & RADEON_FLAG_GTT_WC)
        args.flags |= RADEON_GEM_GTT_WC;

    if (drmCommandWriteRead(rws->fd, DRM_RADEON_GEM_CREATE,
                            &args, sizeof(args))) {
        fprintf(stderr, "radeon: Failed to allocate a buffer:\n");
        fprintf(stderr, "radeon:    size      : %d bytes\n", size);
        fprintf(stderr, "radeon:    alignment : %d bytes\n", desc->alignment);
        fprintf(stderr, "radeon:    domains   : %d\n", args.initial_domain);
        fprintf(stderr, "radeon:    flags     : %d\n", args.flags);
        return NULL;
    }

    bo = CALLOC_STRUCT(radeon_bo);
    if (!bo)
        return NULL;

    pipe_reference_init(&bo->base.reference, 1);
    bo->base.alignment = desc->alignment;
    bo->base.usage = desc->usage;
    bo->base.size = size;
    bo->base.vtbl = &radeon_bo_vtbl;
    bo->mgr = mgr;
    bo->rws = mgr->rws;
    bo->handle = args.handle;
    bo->va = 0;
    bo->initial_domain = rdesc->initial_domains;
    pipe_mutex_init(bo->map_mutex);

    if (mgr->va) {
        struct drm_radeon_gem_va va;

        bo->va = radeon_bomgr_find_va(mgr, size, desc->alignment);

        va.handle = bo->handle;
        va.vm_id = 0;
        va.operation = RADEON_VA_MAP;
        va.flags = RADEON_VM_PAGE_READABLE |
                   RADEON_VM_PAGE_WRITEABLE |
                   RADEON_VM_PAGE_SNOOPED;
        va.offset = bo->va;
        r = drmCommandWriteRead(rws->fd, DRM_RADEON_GEM_VA, &va, sizeof(va));
        if (r && va.operation == RADEON_VA_RESULT_ERROR) {
            fprintf(stderr, "radeon: Failed to allocate virtual address for buffer:\n");
            fprintf(stderr, "radeon:    size      : %d bytes\n", size);
            fprintf(stderr, "radeon:    alignment : %d bytes\n", desc->alignment);
            fprintf(stderr, "radeon:    domains   : %d\n", args.initial_domain);
            fprintf(stderr, "radeon:    va        : 0x%016llx\n", (unsigned long long)bo->va);
            radeon_bo_destroy(&bo->base);
            return NULL;
        }
        pipe_mutex_lock(mgr->bo_handles_mutex);
        if (va.operation == RADEON_VA_RESULT_VA_EXIST) {
            struct pb_buffer *b = &bo->base;
            struct radeon_bo *old_bo =
                util_hash_table_get(mgr->bo_vas, (void*)(uintptr_t)va.offset);

            pipe_mutex_unlock(mgr->bo_handles_mutex);
            pb_reference(&b, &old_bo->base);
            return b;
        }

        util_hash_table_set(mgr->bo_vas, (void*)(uintptr_t)bo->va, bo);
        pipe_mutex_unlock(mgr->bo_handles_mutex);
    }

    if (rdesc->initial_domains & RADEON_DOMAIN_VRAM)
        rws->allocated_vram += align(size, 4096);
    else if (rdesc->initial_domains & RADEON_DOMAIN_GTT)
        rws->allocated_gtt += align(size, 4096);

    return &bo->base;
}

static void radeon_bomgr_flush(struct pb_manager *mgr)
{
    /* NOP */
}

/* This is for the cache bufmgr. */
static boolean radeon_bomgr_is_buffer_busy(struct pb_manager *_mgr,
                                           struct pb_buffer *_buf)
{
   struct radeon_bo *bo = radeon_bo(_buf);

   if (radeon_bo_is_referenced_by_any_cs(bo)) {
       return TRUE;
   }

   if (radeon_bo_is_busy((struct pb_buffer*)bo, RADEON_USAGE_READWRITE)) {
       return TRUE;
   }

   return FALSE;
}

static void radeon_bomgr_destroy(struct pb_manager *_mgr)
{
    struct radeon_bomgr *mgr = radeon_bomgr(_mgr);
    util_hash_table_destroy(mgr->bo_names);
    util_hash_table_destroy(mgr->bo_handles);
    util_hash_table_destroy(mgr->bo_vas);
    pipe_mutex_destroy(mgr->bo_handles_mutex);
    pipe_mutex_destroy(mgr->bo_va_mutex);
    FREE(mgr);
}

#define PTR_TO_UINT(x) ((unsigned)((intptr_t)(x)))

static unsigned handle_hash(void *key)
{
    return PTR_TO_UINT(key);
}

static int handle_compare(void *key1, void *key2)
{
    return PTR_TO_UINT(key1) != PTR_TO_UINT(key2);
}

struct pb_manager *radeon_bomgr_create(struct radeon_drm_winsys *rws)
{
    struct radeon_bomgr *mgr;

    mgr = CALLOC_STRUCT(radeon_bomgr);
    if (!mgr)
        return NULL;

    mgr->base.destroy = radeon_bomgr_destroy;
    mgr->base.create_buffer = radeon_bomgr_create_bo;
    mgr->base.flush = radeon_bomgr_flush;
    mgr->base.is_buffer_busy = radeon_bomgr_is_buffer_busy;

    mgr->rws = rws;
    mgr->bo_names = util_hash_table_create(handle_hash, handle_compare);
    mgr->bo_handles = util_hash_table_create(handle_hash, handle_compare);
    mgr->bo_vas = util_hash_table_create(handle_hash, handle_compare);
    pipe_mutex_init(mgr->bo_handles_mutex);
    pipe_mutex_init(mgr->bo_va_mutex);

    mgr->va = rws->info.r600_virtual_address;
    mgr->va_offset = rws->va_start;
    list_inithead(&mgr->va_holes);

    return &mgr->base;
}

static unsigned eg_tile_split(unsigned tile_split)
{
    switch (tile_split) {
    case 0:     tile_split = 64;    break;
    case 1:     tile_split = 128;   break;
    case 2:     tile_split = 256;   break;
    case 3:     tile_split = 512;   break;
    default:
    case 4:     tile_split = 1024;  break;
    case 5:     tile_split = 2048;  break;
    case 6:     tile_split = 4096;  break;
    }
    return tile_split;
}

static unsigned eg_tile_split_rev(unsigned eg_tile_split)
{
    switch (eg_tile_split) {
    case 64:    return 0;
    case 128:   return 1;
    case 256:   return 2;
    case 512:   return 3;
    default:
    case 1024:  return 4;
    case 2048:  return 5;
    case 4096:  return 6;
    }
}

static void radeon_bo_get_tiling(struct pb_buffer *_buf,
                                 enum radeon_bo_layout *microtiled,
                                 enum radeon_bo_layout *macrotiled,
                                 unsigned *bankw, unsigned *bankh,
                                 unsigned *tile_split,
                                 unsigned *stencil_tile_split,
                                 unsigned *mtilea,
                                 bool *scanout)
{
    struct radeon_bo *bo = get_radeon_bo(_buf);
    struct drm_radeon_gem_set_tiling args;

    memset(&args, 0, sizeof(args));

    args.handle = bo->handle;

    drmCommandWriteRead(bo->rws->fd,
                        DRM_RADEON_GEM_GET_TILING,
                        &args,
                        sizeof(args));

    *microtiled = RADEON_LAYOUT_LINEAR;
    *macrotiled = RADEON_LAYOUT_LINEAR;
    if (args.tiling_flags & RADEON_TILING_MICRO)
        *microtiled = RADEON_LAYOUT_TILED;
    else if (args.tiling_flags & RADEON_TILING_MICRO_SQUARE)
        *microtiled = RADEON_LAYOUT_SQUARETILED;

    if (args.tiling_flags & RADEON_TILING_MACRO)
        *macrotiled = RADEON_LAYOUT_TILED;
    if (bankw && tile_split && stencil_tile_split && mtilea && tile_split) {
        *bankw = (args.tiling_flags >> RADEON_TILING_EG_BANKW_SHIFT) & RADEON_TILING_EG_BANKW_MASK;
        *bankh = (args.tiling_flags >> RADEON_TILING_EG_BANKH_SHIFT) & RADEON_TILING_EG_BANKH_MASK;
        *tile_split = (args.tiling_flags >> RADEON_TILING_EG_TILE_SPLIT_SHIFT) & RADEON_TILING_EG_TILE_SPLIT_MASK;
        *stencil_tile_split = (args.tiling_flags >> RADEON_TILING_EG_STENCIL_TILE_SPLIT_SHIFT) & RADEON_TILING_EG_STENCIL_TILE_SPLIT_MASK;
        *mtilea = (args.tiling_flags >> RADEON_TILING_EG_MACRO_TILE_ASPECT_SHIFT) & RADEON_TILING_EG_MACRO_TILE_ASPECT_MASK;
        *tile_split = eg_tile_split(*tile_split);
    }
    if (scanout)
        *scanout = bo->rws->gen >= DRV_SI && !(args.tiling_flags & RADEON_TILING_R600_NO_SCANOUT);
}

static void radeon_bo_set_tiling(struct pb_buffer *_buf,
                                 struct radeon_winsys_cs *rcs,
                                 enum radeon_bo_layout microtiled,
                                 enum radeon_bo_layout macrotiled,
                                 unsigned bankw, unsigned bankh,
                                 unsigned tile_split,
                                 unsigned stencil_tile_split,
                                 unsigned mtilea,
                                 uint32_t pitch,
                                 bool scanout)
{
    struct radeon_bo *bo = get_radeon_bo(_buf);
    struct radeon_drm_cs *cs = radeon_drm_cs(rcs);
    struct drm_radeon_gem_set_tiling args;

    memset(&args, 0, sizeof(args));

    /* Tiling determines how DRM treats the buffer data.
     * We must flush CS when changing it if the buffer is referenced. */
    if (cs && radeon_bo_is_referenced_by_cs(cs, bo)) {
        cs->flush_cs(cs->flush_data, 0, NULL);
    }

    while (p_atomic_read(&bo->num_active_ioctls)) {
        sched_yield();
    }

    if (microtiled == RADEON_LAYOUT_TILED)
        args.tiling_flags |= RADEON_TILING_MICRO;
    else if (microtiled == RADEON_LAYOUT_SQUARETILED)
        args.tiling_flags |= RADEON_TILING_MICRO_SQUARE;

    if (macrotiled == RADEON_LAYOUT_TILED)
        args.tiling_flags |= RADEON_TILING_MACRO;

    args.tiling_flags |= (bankw & RADEON_TILING_EG_BANKW_MASK) <<
        RADEON_TILING_EG_BANKW_SHIFT;
    args.tiling_flags |= (bankh & RADEON_TILING_EG_BANKH_MASK) <<
        RADEON_TILING_EG_BANKH_SHIFT;
    if (tile_split) {
	args.tiling_flags |= (eg_tile_split_rev(tile_split) &
			      RADEON_TILING_EG_TILE_SPLIT_MASK) <<
	    RADEON_TILING_EG_TILE_SPLIT_SHIFT;
    }
    args.tiling_flags |= (stencil_tile_split &
			  RADEON_TILING_EG_STENCIL_TILE_SPLIT_MASK) <<
        RADEON_TILING_EG_STENCIL_TILE_SPLIT_SHIFT;
    args.tiling_flags |= (mtilea & RADEON_TILING_EG_MACRO_TILE_ASPECT_MASK) <<
        RADEON_TILING_EG_MACRO_TILE_ASPECT_SHIFT;

    if (bo->rws->gen >= DRV_SI && !scanout)
        args.tiling_flags |= RADEON_TILING_R600_NO_SCANOUT;

    args.handle = bo->handle;
    args.pitch = pitch;

    drmCommandWriteRead(bo->rws->fd,
                        DRM_RADEON_GEM_SET_TILING,
                        &args,
                        sizeof(args));
}

static struct radeon_winsys_cs_handle *radeon_drm_get_cs_handle(struct pb_buffer *_buf)
{
    /* return radeon_bo. */
    return (struct radeon_winsys_cs_handle*)get_radeon_bo(_buf);
}

static struct pb_buffer *
radeon_winsys_bo_create(struct radeon_winsys *rws,
                        unsigned size,
                        unsigned alignment,
                        boolean use_reusable_pool,
                        enum radeon_bo_domain domain,
                        enum radeon_bo_flag flags)
{
    struct radeon_drm_winsys *ws = radeon_drm_winsys(rws);
    struct radeon_bomgr *mgr = radeon_bomgr(ws->kman);
    struct radeon_bo_desc desc;
    struct pb_manager *provider;
    struct pb_buffer *buffer;

    memset(&desc, 0, sizeof(desc));
    desc.base.alignment = alignment;

    /* Additional criteria for the cache manager. */
    desc.base.usage = domain;
    desc.initial_domains = domain;
    desc.flags = flags;

    /* Assign a buffer manager. */
    assert(flags < RADEON_NUM_CACHE_MANAGERS);
    if (use_reusable_pool) {
        if (domain == RADEON_DOMAIN_VRAM)
            provider = ws->cman_vram[flags];
        else
            provider = ws->cman_gtt[flags];
    } else {
        provider = ws->kman;
    }

    buffer = provider->create_buffer(provider, size, &desc.base);
    if (!buffer)
        return NULL;

    pipe_mutex_lock(mgr->bo_handles_mutex);
    util_hash_table_set(mgr->bo_handles, (void*)(uintptr_t)get_radeon_bo(buffer)->handle, buffer);
    pipe_mutex_unlock(mgr->bo_handles_mutex);

    return (struct pb_buffer*)buffer;
}

static struct pb_buffer *radeon_winsys_bo_from_handle(struct radeon_winsys *rws,
                                                      struct winsys_handle *whandle,
                                                      unsigned *stride)
{
    struct radeon_drm_winsys *ws = radeon_drm_winsys(rws);
    struct radeon_bo *bo;
    struct radeon_bomgr *mgr = radeon_bomgr(ws->kman);
    int r;
    unsigned handle;
    uint64_t size = 0;

    /* We must maintain a list of pairs <handle, bo>, so that we always return
     * the same BO for one particular handle. If we didn't do that and created
     * more than one BO for the same handle and then relocated them in a CS,
     * we would hit a deadlock in the kernel.
     *
     * The list of pairs is guarded by a mutex, of course. */
    pipe_mutex_lock(mgr->bo_handles_mutex);

    if (whandle->type == DRM_API_HANDLE_TYPE_SHARED) {
        /* First check if there already is an existing bo for the handle. */
        bo = util_hash_table_get(mgr->bo_names, (void*)(uintptr_t)whandle->handle);
    } else if (whandle->type == DRM_API_HANDLE_TYPE_FD) {
        /* We must first get the GEM handle, as fds are unreliable keys */
        r = drmPrimeFDToHandle(ws->fd, whandle->handle, &handle);
        if (r)
            goto fail;
        bo = util_hash_table_get(mgr->bo_handles, (void*)(uintptr_t)handle);
    } else {
        /* Unknown handle type */
        goto fail;
    }

    if (bo) {
        /* Increase the refcount. */
        struct pb_buffer *b = NULL;
        pb_reference(&b, &bo->base);
        goto done;
    }

    /* There isn't, create a new one. */
    bo = CALLOC_STRUCT(radeon_bo);
    if (!bo) {
        goto fail;
    }

    if (whandle->type == DRM_API_HANDLE_TYPE_SHARED) {
        struct drm_gem_open open_arg = {};
        memset(&open_arg, 0, sizeof(open_arg));
        /* Open the BO. */
        open_arg.name = whandle->handle;
        if (drmIoctl(ws->fd, DRM_IOCTL_GEM_OPEN, &open_arg)) {
            FREE(bo);
            goto fail;
        }
        handle = open_arg.handle;
        size = open_arg.size;
        bo->flink_name = whandle->handle;
    } else if (whandle->type == DRM_API_HANDLE_TYPE_FD) {
        size = lseek(whandle->handle, 0, SEEK_END);
        /*
         * Could check errno to determine whether the kernel is new enough, but
         * it doesn't really matter why this failed, just that it failed.
         */
        if (size == (off_t)-1) {
            FREE(bo);
            goto fail;
        }
        lseek(whandle->handle, 0, SEEK_SET);
    }

    bo->handle = handle;

    /* Initialize it. */
    pipe_reference_init(&bo->base.reference, 1);
    bo->base.alignment = 0;
    bo->base.usage = PB_USAGE_GPU_WRITE | PB_USAGE_GPU_READ;
    bo->base.size = (unsigned) size;
    bo->base.vtbl = &radeon_bo_vtbl;
    bo->mgr = mgr;
    bo->rws = mgr->rws;
    bo->va = 0;
    pipe_mutex_init(bo->map_mutex);

    if (bo->flink_name)
        util_hash_table_set(mgr->bo_names, (void*)(uintptr_t)bo->flink_name, bo);

    util_hash_table_set(mgr->bo_handles, (void*)(uintptr_t)bo->handle, bo);

done:
    pipe_mutex_unlock(mgr->bo_handles_mutex);

    if (stride)
        *stride = whandle->stride;

    if (mgr->va && !bo->va) {
        struct drm_radeon_gem_va va;

        bo->va = radeon_bomgr_find_va(mgr, bo->base.size, 1 << 20);

        va.handle = bo->handle;
        va.operation = RADEON_VA_MAP;
        va.vm_id = 0;
        va.offset = bo->va;
        va.flags = RADEON_VM_PAGE_READABLE |
                   RADEON_VM_PAGE_WRITEABLE |
                   RADEON_VM_PAGE_SNOOPED;
        va.offset = bo->va;
        r = drmCommandWriteRead(ws->fd, DRM_RADEON_GEM_VA, &va, sizeof(va));
        if (r && va.operation == RADEON_VA_RESULT_ERROR) {
            fprintf(stderr, "radeon: Failed to assign virtual address space\n");
            radeon_bo_destroy(&bo->base);
            return NULL;
        }
        pipe_mutex_lock(mgr->bo_handles_mutex);
        if (va.operation == RADEON_VA_RESULT_VA_EXIST) {
            struct pb_buffer *b = &bo->base;
            struct radeon_bo *old_bo =
                util_hash_table_get(mgr->bo_vas, (void*)(uintptr_t)va.offset);

            pipe_mutex_unlock(mgr->bo_handles_mutex);
            pb_reference(&b, &old_bo->base);
            return b;
        }

        util_hash_table_set(mgr->bo_vas, (void*)(uintptr_t)bo->va, bo);
        pipe_mutex_unlock(mgr->bo_handles_mutex);
    }

    bo->initial_domain = radeon_bo_get_initial_domain((void*)bo);

    if (bo->initial_domain & RADEON_DOMAIN_VRAM)
        ws->allocated_vram += align(bo->base.size, 4096);
    else if (bo->initial_domain & RADEON_DOMAIN_GTT)
        ws->allocated_gtt += align(bo->base.size, 4096);

    return (struct pb_buffer*)bo;

fail:
    pipe_mutex_unlock(mgr->bo_handles_mutex);
    return NULL;
}

static boolean radeon_winsys_bo_get_handle(struct pb_buffer *buffer,
                                           unsigned stride,
                                           struct winsys_handle *whandle)
{
    struct drm_gem_flink flink;
    struct radeon_bo *bo = get_radeon_bo(buffer);

    memset(&flink, 0, sizeof(flink));

    if (whandle->type == DRM_API_HANDLE_TYPE_SHARED) {
        if (!bo->flink_name) {
            flink.handle = bo->handle;

            if (ioctl(bo->rws->fd, DRM_IOCTL_GEM_FLINK, &flink)) {
                return FALSE;
            }

            bo->flink_name = flink.name;

            pipe_mutex_lock(bo->mgr->bo_handles_mutex);
            util_hash_table_set(bo->mgr->bo_names, (void*)(uintptr_t)bo->flink_name, bo);
            pipe_mutex_unlock(bo->mgr->bo_handles_mutex);
        }
        whandle->handle = bo->flink_name;
    } else if (whandle->type == DRM_API_HANDLE_TYPE_KMS) {
        whandle->handle = bo->handle;
    } else if (whandle->type == DRM_API_HANDLE_TYPE_FD) {
        if (drmPrimeHandleToFD(bo->rws->fd, bo->handle, DRM_CLOEXEC, (int*)&whandle->handle))
            return FALSE;
    }

    whandle->stride = stride;
    return TRUE;
}

static uint64_t radeon_winsys_bo_va(struct radeon_winsys_cs_handle *buf)
{
    return ((struct radeon_bo*)buf)->va;
}

void radeon_bomgr_init_functions(struct radeon_drm_winsys *ws)
{
    ws->base.buffer_get_cs_handle = radeon_drm_get_cs_handle;
    ws->base.buffer_set_tiling = radeon_bo_set_tiling;
    ws->base.buffer_get_tiling = radeon_bo_get_tiling;
    ws->base.buffer_map = radeon_bo_map;
    ws->base.buffer_unmap = radeon_bo_unmap;
    ws->base.buffer_wait = radeon_bo_wait;
    ws->base.buffer_is_busy = radeon_bo_is_busy;
    ws->base.buffer_create = radeon_winsys_bo_create;
    ws->base.buffer_from_handle = radeon_winsys_bo_from_handle;
    ws->base.buffer_get_handle = radeon_winsys_bo_get_handle;
    ws->base.buffer_get_virtual_address = radeon_winsys_bo_va;
    ws->base.buffer_get_initial_domain = radeon_bo_get_initial_domain;
}


text:
package org.springframework.aop.aspectj;

import org.junit.Before;
import org.junit.Test;
import test.mixin.Lockable;

import org.springframework.aop.support.AopUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.tests.Assume;
import org.springframework.tests.TestGroup;
import org.springframework.tests.sample.beans.ITestBean;

import static org.junit.Assert.*;

/**
 * @author Rod Johnson
 * @author Chris Beams
 */
public final class DeclareParentsTests {

	private ITestBean testBeanProxy;

	private ApplicationContext ctx;

	@Before
	public void setUp() throws Exception {
		ctx = new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass());

		testBeanProxy = (ITestBean) ctx.getBean("testBean");
		assertTrue(AopUtils.isAopProxy(testBeanProxy));
	}

	@Test
	public void testIntroductionWasMade() {
		assertTrue("Introduction must have been made", testBeanProxy instanceof Lockable);
	}

	// TODO if you change type pattern from org.springframework.beans..*
	// to org.springframework..* it also matches introduction.
	// Perhaps generated advisor bean definition could be made to depend
	// on the introduction, in which case this would not be a problem.
	@Test
	public void testLockingWorks() {
		Assume.group(TestGroup.LONG_RUNNING);

		Object introductionObject = ctx.getBean("introduction");
		assertFalse("Introduction should not be proxied", AopUtils.isAopProxy(introductionObject));

		Lockable lockable = (Lockable) testBeanProxy;
		assertFalse(lockable.locked());

		// Invoke a non-advised method
		testBeanProxy.getAge();

		testBeanProxy.setName("");
		lockable.lock();
		try {
			testBeanProxy.setName(" ");
			fail("Should be locked");
		}
		catch (IllegalStateException ex) {
			// expected
		}
	}

}

class NonAnnotatedMakeLockable {

	public void checkNotLocked(Lockable mixin) {
		if (mixin.locked()) {
			throw new IllegalStateException("locked");
		}
	}

}


text:
require_relative "../../spec_helper"

describe X509Sleuth::Scanner::Target do
  let(:host_target) { described_class.new("localhost") }
  let(:ip_target) { described_class.new("127.0.0.1") }
  let(:cidr_target) { described_class.new("127.0.0.1/30") }
  let(:ip_subnet_pair_target) { described_class.new("127.0.0.1/255.255.255.248") }

  context "instances" do
    subject { host_target }

    it { should respond_to(:is_a_range?) }
    it { should respond_to(:hosts) }
    it { should respond_to(:target) }
  end

  context "when target is an IPv4 address and CIDR subnet mask" do
    describe "#is_a_range?" do
      it "returns true" do
        expect(cidr_target.is_a_range?).to be true
      end
    end

    describe "#hosts" do
      it "returns the correct host ip addresses" do
        expect(cidr_target.hosts).to have(2).items
        expect(cidr_target.hosts).to include("127.0.0.1", "127.0.0.2")
      end

      it "omits the network and broadcast addresses" do
        expect(cidr_target.hosts).to_not include("127.0.0.0", "127.0.0.3")
      end
    end
  end

  context "when target is an IPv4 address and dotted-decimal subnet mask" do
    describe "#is_a_range?" do
      it "returns true" do
        expect(ip_subnet_pair_target.is_a_range?).to be true
      end
    end

    describe "#hosts" do
      it "returns the correct host ip addresses" do
        expect(ip_subnet_pair_target.hosts).to have(6).items
        expect(ip_subnet_pair_target.hosts).to include(
          "127.0.0.1", "127.0.0.2", "127.0.0.3",
          "127.0.0.4", "127.0.0.5", "127.0.0.6"
        )
      end

      it "omits the network and broadcast addresses" do
        expect(ip_subnet_pair_target.hosts).to_not include("127.0.0.0", "127.0.0.7")
      end
    end
  end

  context "when target is a single IPv4 address" do
    describe "#is_a_range?" do
      it "returns false" do
        expect(ip_target.is_a_range?).to be false
      end
    end

    describe "#hosts" do
      it "returns the lone ip address" do
        expect(ip_target.hosts).to have(1).item
        expect(ip_target.hosts).to include("127.0.0.1")
      end
    end
  end

  context "when target is assumed to be a hostname" do
    describe "#is_a_range?" do
      it "returns false" do
        expect(host_target.is_a_range?).to be false
      end
    end

    describe "#hosts" do
      it "returns the lone hostname" do
        expect(host_target.hosts).to have(1).item
        expect(host_target.hosts).to include("localhost")
      end
    end
  end
end


text:
package solidstack.classgen.bytecode;

import solidstack.classgen.Bytes;
import solidstack.classgen.Types.VMTYPE;
import solidstack.classgen.constants.CClass;

public class InitArray implements Expression
{
	private CClass classInfo;
	private Expression[] values;

	public InitArray( CClass type, Expression... values )
	{
		this.classInfo = type;
		this.values = values;
	}

	@Override
	public VMTYPE vmType()
	{
		throw new UnsupportedOperationException();
	}

	@Override
	public void toByteCode( Bytes bytes )
	{
		ByteCode.iconst( bytes, this.values.length );
		bytes.writeByte( 0xBD ); // anewarray
		bytes.writeShort( this.classInfo.index() );
		int i = 0;
		for( Expression value : this.values )
		{
			bytes.writeByte( 0x59 ); // dup
			ByteCode.iconst( bytes, i++ );
			value.toByteCode( bytes );
			bytes.writeByte( 0x53 ); // aastore
		}
	}
}


text:
package com.adaptris.core.management.vcs;

import java.io.File;
import java.util.List;

/**
 * Basic Version control System interface.
 *
 * @author amcgrath
 * @since 3.0.3
 *
 */
public interface VersionControlSystem {

  /**
   * Will perform an action on the remote repository to confirm that the url and credentials for the connection are valid.
   *
   * @param remoteRepoUrl
   * @param workingCopyUrl
   * @return Revision number
   * @throws VcsException
   */
  public String testConnection(String remoteRepoUrl, File workingCopyUrl) throws VcsException;

  /**
   * Will perform a fresh checkout from the remote repository url to the local working copy url.
   *
   * @param remoteRepoUrl
   * @param workingCopyUrl
   * @return Revision number
   * @throws VcsException
   */
  public String checkout(String remoteRepoUrl, File workingCopyUrl) throws VcsException;

  /**
   * Will perform a fresh checkout from the remote repository url to the local working copy url, to the specified revision number.
   * @param remoteRepoUrl
   * @param workingCopyUrl
   * @param revision
   * @return Revision number
   * @throws VcsException
   */
  public String checkout(String remoteRepoUrl, File workingCopyUrl, String revision) throws VcsException;

  /**
   * Will fetch and update yuour local working copy to the specified revision.
   * @param workingCopyUrl
   * @param revision
   * @return Revision number
   * @throws VcsException
   */
  public String update(File workingCopyUrl, String revision) throws VcsException;

  /**
   * Will fetch and update your local working copy with the latest changes from the remote repository.
   * @param workingCopyUrl
   * @return Revision number
   * @throws VcsException
   */
  public String update(File workingCopyUrl) throws VcsException;

  /**
   * Will send your changes to the remote repository, with the supplied commit message.
   * @param workingCopyUrl
   * @param commitMessage
   * @throws VcsException
   */
  public void commit(File workingCopyUrl, String commitMessage) throws VcsException;

  /**
   * Will recursively check directories and sub directories adding all files for commit to the remote repository.
   * @param workingCopyUrl
   * @throws VcsException
   */
  public void recursiveAdd(File workingCopyUrl) throws VcsException;

  /**
   * Add and commit the list of provided files to the remote repository. Useful when only some files
   * need to be committed.
   *
   * @param workingCopyUrl
   * @param commitMessage
   * @param fileNames relative to the workingCopyUrl
   * @throws VcsException
   */
  public void addAndCommit(File workingCopyUrl, String commitMessage, String... fileNames) throws VcsException;

  /**
   * @return VCS Implementation Name
   */
  public String getImplementationName();

  /**
   * This method will return the remote repositories latest revision number/string/id.
   * @return Revision as a String
   */
  public String getRemoteRevision(String remoteRepoUrl, File workingCopyUrl) throws VcsException;

  /**
   * This method will return your local repositories current revision number/string/id.
   * @return Revision as a String
   */
  public String getLocalRevision(File workingCopyUrl) throws VcsException;

  /**
   *

   * Will return a list of {@link RevisionHistoryItem}'s from the remote repository.
   *

   *

   * The results returned may also be limited by providing a limit > zero. If your supplied limit
   * equals zero then the results will not be limited.
   *

   *
   * @param remoteRepoUrl
   * @return a list of {@link RevisionHistoryItem}s
   * @throws VcsException
   */
  public List<RevisionHistoryItem> getRemoteRevisionHistory(String remoteRepoUrl, File workingCopyUrl, int limit) throws VcsException;

}


text:
package org.elasticsearch.license;

import com.carrotsearch.randomizedtesting.RandomizedTest;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.time.DateFormatter;
import org.elasticsearch.common.time.DateMathParser;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.license.licensor.LicenseSigner;
import org.elasticsearch.protocol.xpack.license.LicensesStatus;
import org.elasticsearch.protocol.xpack.license.PutLicenseResponse;
import org.hamcrest.MatcherAssert;
import org.junit.Assert;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;

import static com.carrotsearch.randomizedtesting.RandomizedTest.randomBoolean;
import static com.carrotsearch.randomizedtesting.RandomizedTest.randomInt;
import static org.apache.lucene.util.LuceneTestCase.createTempFile;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.test.ESTestCase.randomAlphaOfLength;
import static org.elasticsearch.test.ESTestCase.randomFrom;
import static org.elasticsearch.test.ESTestCase.randomIntBetween;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;

public class TestUtils {

    private static final DateFormatter formatDateTimeFormatter = DateFormatter.forPattern("yyyy-MM-dd");
    private static final DateMathParser dateMathParser = formatDateTimeFormatter.toDateMathParser();

    public static String dateMathString(String time, final long now) {
        return formatDateTimeFormatter.format(dateMathParser.parse(time, () -> now).atZone(ZoneOffset.UTC));
    }

    public static long dateMath(String time, final long now) {
        return dateMathParser.parse(time, () -> now).toEpochMilli();
    }

    public static LicenseSpec generateRandomLicenseSpec(int version) {
        boolean datesInMillis = randomBoolean();
        long now = System.currentTimeMillis();
        String uid = UUID.randomUUID().toString();
        String feature = "feature__" + randomInt();
        String issuer = "issuer__"  + randomInt();
        String issuedTo = "issuedTo__" + randomInt();
        final String type;
        final String subscriptionType;
        if (version < License.VERSION_NO_FEATURE_TYPE) {
            subscriptionType = randomFrom("gold", "silver", "platinum");
            type = "subscription";//randomFrom("subscription", "internal", "development");
        } else {
            subscriptionType = null;
            type = randomFrom("basic", "dev", "gold", "silver", "platinum");
        }
        int maxNodes = RandomizedTest.randomIntBetween(5, 100);
        if (datesInMillis) {
            long issueDateInMillis = dateMath("now", now);
            long expiryDateInMillis = dateMath("now+10d/d", now);
            return new LicenseSpec(version, uid, feature, issueDateInMillis, expiryDateInMillis, type, subscriptionType, issuedTo, issuer,
                maxNodes);
        } else {
            String issueDate = dateMathString("now", now);
            String expiryDate = dateMathString("now+10d/d", now);
            return new LicenseSpec(version, uid, feature, issueDate, expiryDate, type, subscriptionType, issuedTo, issuer, maxNodes);
        }
    }

    public static String generateLicenseSpecString(LicenseSpec licenseSpec) throws IOException {
        XContentBuilder licenses = jsonBuilder();
        licenses.startObject();
        licenses.startArray("licenses");
        licenses.startObject()
            .field("uid", licenseSpec.uid)
            .field("type", licenseSpec.type)
            .field("subscription_type", licenseSpec.subscriptionType)
            .field("issued_to", licenseSpec.issuedTo)
            .field("issuer", licenseSpec.issuer)
            .field("feature", licenseSpec.feature)
            .field("max_nodes", licenseSpec.maxNodes);

        if (licenseSpec.issueDate != null) {
            licenses.field("issue_date", licenseSpec.issueDate);
        } else {
            licenses.field("issue_date_in_millis", licenseSpec.issueDateInMillis);
        }
        if (licenseSpec.expiryDate != null) {
            licenses.field("expiry_date", licenseSpec.expiryDate);
        } else {
            licenses.field("expiry_date_in_millis", licenseSpec.expiryDateInMillis);
        }
        licenses.field("version", licenseSpec.version);
        licenses.endObject();
        licenses.endArray();
        licenses.endObject();
        return Strings.toString(licenses);
    }

    public static License generateLicenses(LicenseSpec spec) {
        License.Builder builder = License.builder()
            .uid(spec.uid)
            .feature(spec.feature)
            .type(spec.type)
            .subscriptionType(spec.subscriptionType)
            .issuedTo(spec.issuedTo)
            .issuer(spec.issuer)
            .maxNodes(spec.maxNodes);

        if (spec.expiryDate != null) {
            builder.expiryDate(DateUtils.endOfTheDay(spec.expiryDate));
        } else {
            builder.expiryDate(spec.expiryDateInMillis);
        }
        if (spec.issueDate != null) {
            builder.issueDate(DateUtils.beginningOfTheDay(spec.issueDate));
        } else {
            builder.issueDate(spec.issueDateInMillis);
        }
        return builder.build();
    }

    public static void assertLicenseSpec(LicenseSpec spec, License license) {
        MatcherAssert.assertThat(license.uid(), equalTo(spec.uid));
        MatcherAssert.assertThat(license.issuedTo(), equalTo(spec.issuedTo));
        MatcherAssert.assertThat(license.issuer(), equalTo(spec.issuer));
        MatcherAssert.assertThat(license.type(), equalTo(spec.type));
        MatcherAssert.assertThat(license.maxNodes(), equalTo(spec.maxNodes));
        if (spec.issueDate != null) {
            MatcherAssert.assertThat(license.issueDate(), equalTo(DateUtils.beginningOfTheDay(spec.issueDate)));
        } else {
            MatcherAssert.assertThat(license.issueDate(), equalTo(spec.issueDateInMillis));
        }
        if (spec.expiryDate != null) {
            MatcherAssert.assertThat(license.expiryDate(), equalTo(DateUtils.endOfTheDay(spec.expiryDate)));
        } else {
            MatcherAssert.assertThat(license.expiryDate(), equalTo(spec.expiryDateInMillis));
        }
    }

    public static class LicenseSpec {
        public final int version;
        public final String feature;
        public final String issueDate;
        public final long issueDateInMillis;
        public final String expiryDate;
        public final long expiryDateInMillis;
        public final String uid;
        public final String type;
        public final String subscriptionType;
        public final String issuedTo;
        public final String issuer;
        public final int maxNodes;

        public LicenseSpec(String issueDate, String expiryDate) {
            this(License.VERSION_CURRENT, UUID.randomUUID().toString(), "feature", issueDate, expiryDate, "trial", "none", "customer",
                "elasticsearch", 5);
        }

        public LicenseSpec(int version, String uid, String feature, long issueDateInMillis, long expiryDateInMillis, String type,
                           String subscriptionType, String issuedTo, String issuer, int maxNodes) {
            this.version = version;
            this.feature = feature;
            this.issueDateInMillis = issueDateInMillis;
            this.issueDate = null;
            this.expiryDateInMillis = expiryDateInMillis;
            this.expiryDate = null;
            this.uid = uid;
            this.type = type;
            this.subscriptionType = subscriptionType;
            this.issuedTo = issuedTo;
            this.issuer = issuer;
            this.maxNodes = maxNodes;
        }

        public LicenseSpec(int version, String uid, String feature, String issueDate, String expiryDate, String type,
                           String subscriptionType, String issuedTo, String issuer, int maxNodes) {
            this.version = version;
            this.feature = feature;
            this.issueDate = issueDate;
            this.issueDateInMillis = -1;
            this.expiryDate = expiryDate;
            this.expiryDateInMillis = -1;
            this.uid = uid;
            this.type = type;
            this.subscriptionType = subscriptionType;
            this.issuedTo = issuedTo;
            this.issuer = issuer;
            this.maxNodes = maxNodes;
        }
    }
    private static Path getTestPriKeyPath() throws Exception {
        return getResourcePath("/private.key");
    }

    private static Path getTestPubKeyPath() throws Exception {
        return getResourcePath("/public.key");
    }

    public static String dumpLicense(License license) throws Exception {
        XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
        builder.startObject();
        builder.startObject("license");
        license.toInnerXContent(builder, ToXContent.EMPTY_PARAMS);
        builder.endObject();
        builder.endObject();
        return Strings.toString(builder);
    }

    public static License generateSignedLicense(TimeValue expiryDuration) throws Exception {
        return generateSignedLicense(null, -1, expiryDuration);
    }

    public static License generateSignedLicense(String type, TimeValue expiryDuration) throws Exception {
        return generateSignedLicense(type, -1, expiryDuration);
    }

    public static License generateSignedLicense(long issueDate, TimeValue expiryDuration) throws Exception {
        return generateSignedLicense(null, issueDate, expiryDuration);
    }

    public static License generateSignedLicense(String type, long issueDate, TimeValue expiryDuration) throws Exception {
        return generateSignedLicense(type, randomIntBetween(License.VERSION_START, License.VERSION_CURRENT), issueDate, expiryDuration);
    }

    public static License generateSignedLicenseOldSignature() {
        long issueDate = System.currentTimeMillis();
        License.Builder specBuilder = License.builder()
                .uid(UUID.randomUUID().toString())
                .version(License.VERSION_START_DATE)
                .issuedTo("customer")
                .maxNodes(5)
                .type("trial")
                .issueDate(issueDate)
                .expiryDate(issueDate + TimeValue.timeValueHours(24).getMillis());
        return SelfGeneratedLicense.create(specBuilder, License.VERSION_START_DATE);
    }

    /**
     * This method which chooses the license type randomly if the type is null. However, it will not randomly
     * choose trial or basic types as those types can only be self-generated.
     */
    public static License generateSignedLicense(String type, int version, long issueDate, TimeValue expiryDuration) throws Exception {
        long issue = (issueDate != -1L) ? issueDate : System.currentTimeMillis() - TimeValue.timeValueHours(2).getMillis();
        final String licenseType;
        if (version < License.VERSION_NO_FEATURE_TYPE) {
            licenseType = randomFrom("subscription", "internal", "development");
        } else {
            licenseType = (type != null) ? type : randomFrom("silver", "dev", "gold", "platinum");
        }
        final License.Builder builder = License.builder()
                .uid(UUID.randomUUID().toString())
                .version(version)
                .expiryDate(System.currentTimeMillis() + expiryDuration.getMillis())
                .issueDate(issue)
                .type(licenseType)
                .issuedTo("customer")
                .issuer("elasticsearch")
                .maxNodes(5);
        if (version == License.VERSION_START) {
            builder.subscriptionType((type != null) ? type : randomFrom("dev", "gold", "platinum", "silver"));
            builder.feature(randomAlphaOfLength(10));
        }
        if ("enterprise".equals(licenseType)) {
            builder.version(License.VERSION_ENTERPRISE)
                .maxResourceUnits(randomIntBetween(5, 500))
                .maxNodes(-1);
        }
        final LicenseSigner signer = new LicenseSigner(getTestPriKeyPath(), getTestPubKeyPath());
        return signer.sign(builder.build());
    }

    public static License generateSignedLicense(License.Builder builder) throws Exception {
        LicenseSigner signer = new LicenseSigner(getTestPriKeyPath(), getTestPubKeyPath());
        return signer.sign(builder.build());
    }

    public static License generateExpiredNonBasicLicense(long expiryDate) throws Exception {
        return generateExpiredNonBasicLicense(randomFrom("silver", "dev", "gold", "platinum"), expiryDate);
    }

    public static License generateExpiredNonBasicLicense() throws Exception {
        return generateExpiredNonBasicLicense(randomFrom("silver", "dev", "gold", "platinum"));
    }

    public static License generateExpiredNonBasicLicense(String type) throws Exception {
        return generateExpiredNonBasicLicense(type,
                System.currentTimeMillis() - TimeValue.timeValueHours(randomIntBetween(1, 10)).getMillis());
    }

    public static License generateExpiredNonBasicLicense(String type, long expiryDate) throws Exception {
        final License.Builder builder = License.builder()
                .uid(UUID.randomUUID().toString())
                .version(License.VERSION_CURRENT)
                .expiryDate(expiryDate)
                .issueDate(expiryDate - TimeValue.timeValueMinutes(10).getMillis())
                .type(type)
                .issuedTo("customer")
                .issuer("elasticsearch")
                .maxNodes(5);
        LicenseSigner signer = new LicenseSigner(getTestPriKeyPath(), getTestPubKeyPath());
        return signer.sign(builder.build());
    }

    private static Path getResourcePath(String resource) throws Exception {
        Path resourceFile = createTempFile();
        try (InputStream resourceInput = TestUtils.class.getResourceAsStream(resource)) {
            Files.copy(resourceInput, resourceFile, StandardCopyOption.REPLACE_EXISTING);
        }
        return resourceFile;
    }

    public static void registerAndAckSignedLicenses(final LicenseService licenseService, License license,
                                                    final LicensesStatus expectedStatus) {
        PutLicenseRequest putLicenseRequest = new PutLicenseRequest().license(license).acknowledge(true);
        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicReference<LicensesStatus> status = new AtomicReference<>();
        licenseService.registerLicense(putLicenseRequest, new ActionListener<PutLicenseResponse>() {
            @Override
            public void onResponse(PutLicenseResponse licensesUpdateResponse) {
                status.set(licensesUpdateResponse.status());
                latch.countDown();
            }

            @Override
            public void onFailure(Exception e) {
                latch.countDown();
            }
        });
        try {
            latch.await();
        } catch (InterruptedException e) {
            Assert.fail(e.getMessage());
        }
        assertThat(status.get(), equalTo(expectedStatus));
    }

    public static class AssertingLicenseState extends XPackLicenseState {
        public final List<License.OperationMode> modeUpdates = new ArrayList<>();
        public final List<Boolean> activeUpdates = new ArrayList<>();
        public final List<Version> trialVersionUpdates = new ArrayList<>();
        public final List<Long> expirationDateUpdates = new ArrayList<>();

        public AssertingLicenseState() {
            super(Settings.EMPTY, () -> 0);
        }

        @Override
        void update(License.OperationMode mode, boolean active, long expirationDate, Version mostRecentTrialVersion) {
            modeUpdates.add(mode);
            activeUpdates.add(active);
            expirationDateUpdates.add(expirationDate);
            trialVersionUpdates.add(mostRecentTrialVersion);
        }
    }

    /**
     * A license state that makes the {@link #update(License.OperationMode, boolean, long, Version)}
     * method public for use in tests.
     */
    public static class UpdatableLicenseState extends XPackLicenseState {
        public UpdatableLicenseState() {
            this(Settings.EMPTY);
        }

        public UpdatableLicenseState(Settings settings) {
            super(settings, () -> 0);
        }

        @Override
        public void update(License.OperationMode mode, boolean active, long expirationDate, Version mostRecentTrialVersion) {
            super.update(mode, active, expirationDate, mostRecentTrialVersion);
        }
    }

    public static XPackLicenseState newTestLicenseState() {
        return new XPackLicenseState(Settings.EMPTY, () -> 0);
    }

    public static void putLicense(Metadata.Builder builder, License license) {
        builder.putCustom(LicensesMetadata.TYPE, new LicensesMetadata(license, null));
    }
}


text:
STATUS_TRACKING

        <form action="<?php echo $action; ?>" method="post">

Description <?php echo form_error('description') ?>
            <textarea class="form-control" rows="3" name="description" id="description" placeholder="Description"><?php echo $description; ?></textarea>

	    <input type="hidden" name="id_status_tracking" value="<?php echo $id_status_tracking; ?>" />

<button type="submit" class="btn btn-primary"><?php echo $button ?></button>
	    <a href="<?php echo site_url('status_tracking') ?>" class="btn btn-default">Back

</form>


text:
package test

import akka.actor.ActorSystem
import akka.pattern.AskTimeoutException
import github.gphat.datadog._
import java.nio.charset.StandardCharsets
import org.json4s._
import org.json4s.native.JsonMethods._
import org.specs2.mutable.Specification
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Await,Future,Promise}
import scala.util.Try
import spray.http._

class TimeboardSpec extends Specification {

  implicit val formats = DefaultFormats

  // Sequential because it's less work to share the client instance
  sequential

  "Client" should {

    val adapter = new OkHttpAdapter()
    val client = new Client(
      apiKey = "apiKey",
      appKey = "appKey",
      httpAdapter = adapter
    )

    "handle get all timeboards" in {
      val res = Await.result(client.getAllTimeboards, Duration(5, "second"))

      res.statusCode must beEqualTo(200)
      adapter.getRequest must beSome.which(_.uri.toString == "https://app.datadoghq.com/api/v1/dash?api_key=apiKey&application_key=appKey")
      adapter.getRequest must beSome.which(_.method == HttpMethods.GET)
    }

    "handle add timeboard" in {
      val res = Await.result(client.addTimeboard("POOP"), Duration(5, "second"))

      res.statusCode must beEqualTo(200)
      adapter.getRequest must beSome.which(_.uri.toString == "https://app.datadoghq.com/api/v1/dash?api_key=apiKey&application_key=appKey")
      adapter.getRequest must beSome.which(_.entity.asString == "POOP")

      adapter.getRequest must beSome.which(_.method == HttpMethods.POST)
    }

    "handle get timeboard" in {
      val res = Await.result(client.getTimeboard(12345), Duration(5, "second"))

      res.statusCode must beEqualTo(200)
      adapter.getRequest must beSome.which(_.uri.toString == "https://app.datadoghq.com/api/v1/dash/12345?api_key=apiKey&application_key=appKey")
      adapter.getRequest must beSome.which(_.method == HttpMethods.GET)
    }

    "handle delete timeboard" in {
      val res = Await.result(client.deleteTimeboard(12345), Duration(5, "second"))

      res.statusCode must beEqualTo(200)
      adapter.getRequest must beSome.which(_.uri.toString == "https://app.datadoghq.com/api/v1/dash/12345?api_key=apiKey&application_key=appKey")

      adapter.getRequest must beSome.which(_.method == HttpMethods.DELETE)
    }

    "handle update timeboard" in {
      val res = Await.result(client.updateTimeboard(12345, "POOP"), Duration(5, "second"))

      res.statusCode must beEqualTo(200)
      adapter.getRequest must beSome.which(_.uri.toString == "https://app.datadoghq.com/api/v1/dash/12345?api_key=apiKey&application_key=appKey")
      adapter.getRequest must beSome.which(_.entity.asString == "POOP")

      adapter.getRequest must beSome.which(_.method == HttpMethods.PUT)
    }
  }
}


text:
    <head<>

one

two
three

four