text:
/
    uint8_t access = NONE;
    for (rt = m_rts.begin(); rt != m_rts.end(); ++rt)
    {
        if (rt->second.m_props != props)
        {
            continue;
        }
        access |= rt->second.m_access;
    }
    /* Add the resource */
    for (rt = m_rts.begin(); rt != m_rts.end(); ++rt)
    {
        if (rt->second.m_props != props)
        {
            continue;
        }
        break;
    }
    if (rt == m_rts.end())
    {
        return OC_STACK_OK;
    }
    OCStackResult result = ::CreateResource(handle, ToUri(path).c_str(), rt->first.c_str(),
            (access & READ) ? OC_RSRVD_INTERFACE_READ : OC_RSRVD_INTERFACE_READ_WRITE,
            VirtualResource::EntityHandlerCB, this, props);
    /*
     * Note that rt is not incremented before calling OCBindResourceTypeToResource.  This is to
     * enable binding new resource types to existing resources (such as binding "oic.d.foo" to
     * "/oic/d").
     */
    for (; (rt != m_rts.end()) && (result == OC_STACK_OK); ++rt)
    {
        if (rt->second.m_props != props)
        {
            continue;
        }
        result = OCBindResourceTypeToResource(*handle, rt->first.c_str());
    }
    if ((access & (READ | READWRITE)) == (READ | READWRITE))
    {
        result = OCBindResourceInterfaceToResource(*handle, OC_RSRVD_INTERFACE_READ_WRITE);
    }
    if (result == OC_STACK_OK)
    {
        LOG(LOG_INFO, "[%p] Created VirtualResource uri=%s", this, OCGetResourceUri(*handle));
        uint8_t n = 0;
        OCGetNumberOfResourceTypes(*handle, &n);
        for (uint8_t i = 0; i < n; ++i)
        {
            LOG(LOG_INFO, "[%p]     rt=%s", this, OCGetResourceTypeName(*handle, i));
        }
        OCGetNumberOfResourceInterfaces(*handle, &n);
        for (uint8_t i = 0; i < n; ++i)
        {
            LOG(LOG_INFO, "[%p]     if=%s", this, OCGetResourceInterfaceName(*handle, i));
        }
    }
    else
    {
        LOG(LOG_ERR, "[%p] Create VirtualResource - %d", this, result);
    }
    return result;
}

OCStackResult VirtualResource::CreateResources()
{
    OCStackResult result;
    size_t numIfaces = GetInterfaces(NULL, 0);
    const ajn::InterfaceDescription **ifaces = new const ajn::InterfaceDescription*[numIfaces];
    GetInterfaces(ifaces, numIfaces);
    for (size_t i = 0; i < numIfaces; ++i)
    {
        const char *ifaceName = ifaces[i]->GetName();
        if (!TranslateInterface(ifaceName))
        {
            continue;
        }
        uint8_t secure = 0;
        ajn::InterfaceSecurityPolicy secPolicy = ifaces[i]->GetSecurityPolicy();
        if (IsSecure() || (secPolicy == ajn::AJ_IFC_SECURITY_REQUIRED) ||
                (IsSecure() && (secPolicy != ajn::AJ_IFC_SECURITY_OFF)))
        {
            secure = OC_SECURE;
        }
        size_t numProps = ifaces[i]->GetProperties(NULL, 0);
        const ajn::InterfaceDescription::Property **props = new const
                ajn::InterfaceDescription::Property*[numProps];
        ifaces[i]->GetProperties(props, numProps);
        for (size_t j = 0; j < numProps; ++j)
        {
            qcc::String value = (props[j]->name == "Version") ? "const" : "false";
            props[j]->GetAnnotation(::ajn::org::freedesktop::DBus::AnnotateEmitsChanged, value);
            std::string rt = GetResourceTypeName(ifaces[i], value);
            if (value == "true" || value == "invalidates")
            {
                m_rts[rt].m_props |= (OC_OBSERVABLE | secure);
            }
            else
            {
                m_rts[rt].m_props |= secure;
            }
            switch (props[j]->access)
            {
                case ajn::PROP_ACCESS_RW:
                case ajn::PROP_ACCESS_WRITE:
                    m_rts[rt].m_access |= READWRITE;
                    break;
                case ajn::PROP_ACCESS_READ:
                    m_rts[rt].m_access |= READ;
                    break;
            }
        }
        delete[] props;
        size_t numMembers = ifaces[i]->GetMembers(NULL, 0);
        const ajn::InterfaceDescription::Member **members = new const
                ajn::InterfaceDescription::Member*[numMembers];
        ifaces[i]->GetMembers(members, numMembers);
        for (size_t j = 0; j < numMembers; ++j)
        {
            std::string rt = GetResourceTypeName(ifaces[i], members[j]->name);
            if (members[j]->memberType == ajn::MESSAGE_METHOD_CALL)
            {
                m_rts[rt].m_access |= READWRITE;
                m_rts[rt].m_props |= secure;
            }
            else if (members[j]->memberType == ajn::MESSAGE_SIGNAL)
            {
                if (members[j]->isSessionlessSignal)
                {
                    m_hasSessionlessSignals = true;
                }
                m_rts[rt].m_access |= READ;
                m_rts[rt].m_props |= (OC_OBSERVABLE | secure);
                m_bus->RegisterSignalHandler(this,
                        static_cast<ajn::MessageReceiver::SignalHandler>(&VirtualResource::SignalCB),
                        members[j], GetPath().c_str());
            }
        }
        delete[] members;
        size_t numAnnotations = ifaces[i]->GetAnnotations();
        qcc::String *names = new qcc::String[numAnnotations];
        qcc::String *values = new qcc::String[numAnnotations];
        ifaces[i]->GetAnnotations(names, values, numAnnotations);
        for (size_t j = 0; j < numAnnotations; ++j)
        {
            if (names[j].find("org.alljoyn.Bus.Struct.") == 0)
            {
                size_t pos = sizeof("org.alljoyn.Bus.Struct.") - 1;
                size_t dot = names[j].find(".", pos);
                if (dot == qcc::String::npos)
                {
                    continue;
                }
                qcc::String structName = "[" + names[j].substr(pos, dot - pos) + "]";
                pos = dot + sizeof(".Field.") - 1;
                dot = names[j].find(".", pos);
                if (dot == qcc::String::npos)
                {
                    continue;
                }
                qcc::String fieldName = names[j].substr(pos, dot - pos);
                Types::m_structs[structName].push_back(Types::Field(fieldName, values[j]));
            }
        }
        delete[] names;
        delete[] values;
        if (!numProps && !numMembers)
        {
            std::string rt = GetResourceTypeName(ifaceName);
            m_rts[rt].m_access |= READ;
            m_rts[rt].m_props |= secure;
        }
    }
    delete[] ifaces;
    if (m_rts.empty())
    {
        LOG(LOG_INFO, "No translatable interfaces");
        return OC_STACK_NO_RESOURCE;
    }

    const ajn::InterfaceDescription *iface = m_bus->GetInterface(
        ::ajn::org::freedesktop::DBus::Properties::InterfaceName);
    assert(iface);
    const ajn::InterfaceDescription::Member *signal = iface->GetSignal("PropertiesChanged");
    assert(signal);
    m_bus->RegisterSignalHandler(this,
            static_cast<ajn::MessageReceiver::SignalHandler>(&VirtualResource::SignalCB),
            signal, GetPath().c_str());

    /* First see if we need more than one resource to translate this object */
    std::map<std::string, ResourceType>::iterator rt = m_rts.begin();
    uint8_t props = rt->second.m_props;
    for (; rt != m_rts.end(); ++rt)
    {
        if (rt->second.m_props != props)
        {
            /* Need multiple resources */
            break;
        }
    }
    /* Next create the resource(s) */
    if (rt == m_rts.end())
    {
        result = CreateResource(&m_handle, GetPath(), OC_DISCOVERABLE | props);
    }
    else
    {
        result = ::CreateResource(&m_handle, ToUri(GetPath()).c_str(), "oic.r.alljoynobject", OC_RSRVD_INTERFACE_LL,
                NULL, this, OC_DISCOVERABLE | OC_OBSERVABLE);
        if (result == OC_STACK_OK)
        {
            result = OCBindResourceTypeToResource(m_handle, OC_RSRVD_RESOURCE_TYPE_COLLECTION);
        }
#ifdef __WITH_DTLS__
        static const uint8_t ps[] = { OC_DISCOVERABLE,
                                      OC_DISCOVERABLE | OC_OBSERVABLE,
                                      OC_DISCOVERABLE | OC_SECURE,
                                      OC_DISCOVERABLE | OC_OBSERVABLE | OC_SECURE,
                                    };
#else
        static const uint8_t ps[] = { OC_DISCOVERABLE,
                                      OC_DISCOVERABLE | OC_OBSERVABLE,
                                    };
#endif
        for (size_t i = 0; (result == OC_STACK_OK) && (i < (sizeof(ps) / sizeof(ps[0]))); ++i)
        {
            OCResourceHandle handle;
            std::string path = GetPath() + "/" + std::to_string(ps[i]);
            result = CreateResource(&handle, path, ps[i]);
            if (result == OC_STACK_OK)
            {
                result = OCBindResource(m_handle, handle);
            }
        }
        if (result == OC_STACK_OK)
        {
            LOG(LOG_INFO, "[%p] Created VirtualResource uri=%s", this, OCGetResourceUri(m_handle));
        }
        else
        {
            LOG(LOG_ERR, "[%p] Create VirtualResource - %d", this, result);
        }
    }
    return result;
}

static std::string GetResourceType(OCResourceHandle resource,
        std::map<std::string, std::string> &query)
{
    std::string rt;
    if (query.find(OC_RSRVD_RESOURCE_TYPE) != query.end())
    {
        rt = query[OC_RSRVD_RESOURCE_TYPE];
    }
    else
    {
        uint8_t n = 0;
        if ((OCGetNumberOfResourceTypes(resource, &n) == OC_STACK_OK) && (n == 1))
        {
            rt = OCGetResourceTypeName(resource, 0);
        }
    }
    return rt;
}

static uint8_t GetAccess(std::map<std::string, std::string> &query)
{
    uint8_t access = NONE;
    if (query.find(OC_RSRVD_INTERFACE) != query.end())
    {
        if (query[OC_RSRVD_INTERFACE] == OC_RSRVD_INTERFACE_DEFAULT)
        {
            access = READWRITE;
        }
        else if (query[OC_RSRVD_INTERFACE] == OC_RSRVD_INTERFACE_READ_WRITE)
        {
            access = READWRITE;
        }
        else if (query[OC_RSRVD_INTERFACE] == OC_RSRVD_INTERFACE_READ)
        {
            access = READ;
        }
    }
    return access;
}

/* Filter properties based on resource type and interface requested. */
static bool ToFilteredOCPayload(OCRepPayload *payload, const std::string ajSoftwareVersion,
        const ajn::InterfaceDescription *iface, const char *emitsChangedValue, uint8_t access,
        const ajn::MsgArg *dict)
{
    bool success = true;
    size_t numEntries = dict->v_array.GetNumElements();
    for (size_t i = 0; success && i < numEntries; ++i)
    {
        const ajn::MsgArg *entry = &dict->v_array.GetElements()[i];
        const char *key = entry->v_dictEntry.key->v_string.str;
        const ajn::InterfaceDescription::Property *property = iface->GetProperty(key);
        if (property)
        {
            if ((access == READWRITE) && (property->access == ajn::PROP_ACCESS_READ))
            {
                continue;
            }
            qcc::String emitsChanged = (property->name == "Version") ? "const" : "false";
            property->GetAnnotation(::ajn::org::freedesktop::DBus::AnnotateEmitsChanged,
                    emitsChanged);
            if (strcmp(emitsChangedValue, emitsChanged.c_str()))
            {
                continue;
            }
            /*
             * Annotations prior to v16.10.00 are not guaranteed to
             * appear in the order they were specified, so are
             * unreliable.
             */
            qcc::String signature = property->signature;
            if (ajSoftwareVersion >= "v16.10.00")
            {
                property->GetAnnotation("org.alljoyn.Bus.Type.Name", signature);
            }
            qcc::String propName = ToOCPropName(GetPropName(iface, emitsChanged + "." + key));
            success = ToOCPayload(payload, propName.c_str(),
                    GetPropType(property, entry->v_dictEntry.val->v_variant.val),
                    entry->v_dictEntry.val->v_variant.val, signature.c_str());
        }
    }
    return success;
}

struct MethodCallContext
{
    std::string m_ajSoftwareVersion;
    std::string m_rt;
    uint8_t m_access;
    const ajn::InterfaceDescription::Member *m_member;
    OCEntityHandlerResponse *m_response;
    MethodCallContext(std::string ajSoftwareVersion, std::string &rt, uint8_t access,
                      const ajn::InterfaceDescription::Member *member,
                      OCEntityHandlerRequest *request)
        : m_ajSoftwareVersion(ajSoftwareVersion), m_rt(rt), m_access(access), m_member(member),
          m_response(NULL)
    {
        m_response = (OCEntityHandlerResponse *) calloc(1, sizeof(OCEntityHandlerResponse));
        m_response->requestHandle = request->requestHandle;
        m_response->resourceHandle = request->resource;
    }
    ~MethodCallContext()
    {
        free(m_response);
    }
};

struct VirtualResource::SetContext
{
    std::string m_ajSoftwareVersion;
    OCRepPayload *m_payload;
    OCRepPayloadValue *m_value;
    OCEntityHandlerResponse *m_response;
    SetContext(std::string ajSoftwareVersion, OCEntityHandlerRequest *request)
        : m_ajSoftwareVersion(ajSoftwareVersion),
          m_payload(OCRepPayloadClone((OCRepPayload *) request->payload)), m_value(m_payload->values),
          m_response(NULL)
    {
        m_response = (OCEntityHandlerResponse *) calloc(1, sizeof(OCEntityHandlerResponse));
        m_response->requestHandle = request->requestHandle;
        m_response->resourceHandle = request->resource;
    }
    ~SetContext()
    {
        free(m_response);
        OCPayloadDestroy((OCPayload *) m_payload);
    }
};

struct VirtualResource::GetAllContext
{
    std::string m_ajSoftwareVersion;
    uint8_t m_access;
    const ajn::InterfaceDescription **m_ifaces;
    size_t m_numIfaces;
    size_t m_iface;
    OCRepPayload *m_payload;
    OCEntityHandlerResponse *m_response;
    GetAllContext(std::string ajSoftwareVersion, uint8_t access,
            const ajn::InterfaceDescription **ifaces, size_t numIfaces, OCRepPayload *payload,
            OCEntityHandlerRequest *request)
        : m_ajSoftwareVersion(ajSoftwareVersion), m_access(access), m_ifaces(ifaces),
          m_numIfaces(numIfaces), m_iface(0), m_payload(payload), m_response(NULL)
    {
        m_response = (OCEntityHandlerResponse *) calloc(1, sizeof(OCEntityHandlerResponse));
        m_response->requestHandle = request->requestHandle;
        m_response->resourceHandle = request->resource;
    }
    ~GetAllContext()
    {
        delete[] m_ifaces;
        OCRepPayloadDestroy(m_payload);
        free(m_response);
    }
};

OCDiagnosticPayload *VirtualResource::CreatePayload(ajn::Message &msg,
        OCEntityHandlerResult *ehResult)
{
    *ehResult = OC_EH_ERROR;
    OCDiagnosticPayload *payload = NULL;
    qcc::String description;
    const char *name = msg->GetErrorName(&description);
    if (name)
    {
        static const std::string ErrorPrefix = "org.openconnectivity.Error.";
        std::string message = name;
        if (message.compare(0, ErrorPrefix.size(), ErrorPrefix) == 0)
        {
            message = message.substr(ErrorPrefix.size());
            static const std::string CodePrefix = "Code";
            if (message.compare(0, CodePrefix.size(), CodePrefix) == 0)
            {
                message = message.substr(CodePrefix.size());
            }
            char *endptr = NULL;
            unsigned long code = strtoul(message.c_str(), &endptr, 10);
            if (*endptr == '\0')
            {
                *ehResult = (OCEntityHandlerResult) code;
            }
            message = description;
        }
        else
        {
            message = message + ": " + description;
        }
        payload = OCDiagnosticPayloadCreate(message.c_str());
    }
    return payload;
}

OCRepPayload *VirtualResource::CreatePayload(const char *uri)
{
    OCRepPayload *payload = OCRepPayloadCreate();
    if (payload)
    {
        OCRepPayloadSetUri(payload, uri);
    }
    return payload;
}

OCStackResult VirtualResource::SetMemberPayload(OCRepPayload *payload,
        const char *ifaceName, const char *memberName)
{
    const ajn::InterfaceDescription *iface = m_bus->GetInterface(ifaceName);
    if (!iface)
    {
        LOG(LOG_INFO, "No such interface %s", ifaceName);
        return OC_STACK_ERROR;
    }
    const ajn::InterfaceDescription::Member *member = iface->GetMember(memberName);
    if (!member)
    {
        LOG(LOG_INFO, "No such member %s.%s", ifaceName, memberName);
        return OC_STACK_ERROR;
    }
    qcc::String signature = member->signature + member->returnSignature;
    size_t numArgs = CountCompleteTypes(signature.c_str());
    const char *argNames = member->argNames.c_str();
    std::string propName = GetPropName(member, "validity");
    OCRepPayloadSetPropBool(payload, propName.c_str(), false);
    for (size_t i = 0; i < numArgs; ++i)
    {
        propName = GetPropName(member, NextArgName(argNames), i);
        OCRepPayloadSetNull(payload, propName.c_str());
    }
    return OC_STACK_OK;
}

OCEntityHandlerResult VirtualResource::EntityHandlerCB(OCEntityHandlerFlag flag,
        OCEntityHandlerRequest *request,
        void *ctx)
{
    LOG(LOG_INFO, "[%p] flag=%x,request=%p,ctx=%p", ctx, flag, request, ctx);
    if (!IsValidRequest(request))
    {
        LOG(LOG_INFO, "Invalid request received");
        return OC_EH_BAD_REQ;
    }

    VirtualResource *resource = reinterpret_cast<VirtualResource *>(ctx);
    std::lock_guard<std::mutex> lock(resource->m_mutex);
    const char *uri = OCGetResourceUri(request->resource);
    std::map<std::string, std::string> queryMap = ParseQuery(request->resource, request->query);
    std::string rt = GetResourceType(request->resource, queryMap);
    uint8_t access = GetAccess(queryMap);
    LOG(LOG_INFO, "[%p] uri=%s,query=%s,rt=%s,access=%d", resource, uri, request->query, rt.c_str(),
            access);
    if (flag & OC_OBSERVE_FLAG)
    {
        if (request->obsInfo.action == OC_OBSERVE_REGISTER)
        {
            Observation key(request->resource, request->query);
            std::vector<OCObservationId>::iterator it = std::find(resource->m_observers[key].begin(),
                    resource->m_observers[key].end(), request->obsInfo.obsId);
            if (it == resource->m_observers[key].end())
            {
                LOG(LOG_INFO, "[%p] Register observer rt=%s,obsId=%d", resource, rt.c_str(),
                        request->obsInfo.obsId);
                resource->m_observers[key].push_back(request->obsInfo.obsId);
            }
            /* Add match rule for sessionless signal */
            if (resource->m_hasSessionlessSignals)
            {
                std::string rule;
                std::string ifaceName = ::GetInterface(rt);
                std::string memberName = GetMember(rt);
                if (memberName.empty())
                {
                    rule = "type='signal',sender='" +
                            std::string(resource->GetUniqueName().c_str()) + "',sessionless='t'";
                }
                else
                {
                    const ajn::InterfaceDescription *iface = resource->GetInterface(ifaceName.c_str());
                    if (!iface)
                    {
                        LOG(LOG_INFO, "[%p] Observe invalid iface %s", resource, ifaceName.c_str());
                        return OC_EH_ERROR;
                    }
                    const ajn::InterfaceDescription::Member *signal = iface->GetSignal(memberName.c_str());
                    if (signal && signal->isSessionlessSignal)
                    {
                        rule = "type='signal',sender='" +
                                std::string(resource->GetUniqueName().c_str()) + "',interface='" +
                                ifaceName + "',member='" + memberName + "',sessionless='t'";
                    }
                }
                if (!rule.empty())
                {
                    QStatus status = resource->m_bus->AddMatchAsync(rule.c_str(), resource);
                    if (status == ER_OK)
                    {
                        LOG(LOG_INFO, "AddMatchAsync(%s)", rule.c_str());
                        resource->m_matchRules[request->obsInfo.obsId] = rule;
                    }
                    else
                    {
                        LOG(LOG_ERR, "AddMatchAsync - %s", QCC_StatusText(status));
                    }
                }
            }
        }
        else if (request->obsInfo.action == OC_OBSERVE_DEREGISTER)
        {
            for (std::map<Observation, std::vector<OCObservationId>>::iterator it =
                     resource->m_observers.begin(); it != resource->m_observers.end(); ++it)
            {
                for (std::vector<OCObservationId>::iterator jt = it->second.begin();
                     jt != it->second.end(); ++jt)
                {
                    if (*jt == request->obsInfo.obsId)
                    {
                        LOG(LOG_INFO, "[%p] Deregister observer %s %d", resource,
                                it->first.m_query.c_str(), request->obsInfo.obsId);
                        if (!resource->m_matchRules[request->obsInfo.obsId].empty())
                        {
                            QStatus status = resource->m_bus->RemoveMatchAsync(
                                resource->m_matchRules[request->obsInfo.obsId].c_str(), resource);
                            if (status != ER_OK)
                            {
                                LOG(LOG_ERR, "RemoveMatchAsync - %s", QCC_StatusText(status));
                            }
                        }
                        it->second.erase(jt);
                        goto handleRequest;
                    }
                }
            }
        }
    }
handleRequest:
    OCEntityHandlerResult result;
    switch (request->method)
    {
        case OC_REST_GET:
            {
                std::string ifaceName = ::GetInterface(rt);
                std::string memberName = GetMember(rt);
                if (queryMap[OC_RSRVD_INTERFACE] == OC_RSRVD_INTERFACE_DEFAULT)
                {
                    /*
                     * Reset access for baseline query so that we fetch all properties, not only
                     * the readwrite ones.
                     */
                    access = READ;
                }
                if (memberName.empty())
                {
                    size_t numIfaces = resource->GetInterfaces(NULL, 0);
                    const ajn::InterfaceDescription **ifaces =
                            new const ajn::InterfaceDescription*[numIfaces];
                    resource->GetInterfaces(ifaces, numIfaces);
                    OCRepPayload *payload = resource->CreatePayload(uri);
                    GetAllContext *context = new GetAllContext(resource->m_ajSoftwareVersion, access,
                            ifaces, numIfaces, payload, request);
                    QStatus status = resource->GetAll(context);
                    if (status == ER_OK)
                    {
                        result = OC_EH_OK;
                    }
                    else
                    {
                        LOG(LOG_ERR, "GetAll - %s", QCC_StatusText(status));
                        delete context;
                        result = OC_EH_ERROR;
                    }
                }
                else if (memberName == "const" || memberName == "true" || memberName == "false"
                         || memberName == "invalidates")
                {
                    ajn::MsgArg arg("s", ifaceName.c_str());
                    const ajn::InterfaceDescription *iface = resource->m_bus->GetInterface(
                                ::ajn::org::freedesktop::DBus::Properties::InterfaceName);
                    assert(iface);
                    const ajn::InterfaceDescription::Member *member = iface->GetMember("GetAll");
                    assert(member);
                    MethodCallContext *context = new MethodCallContext(resource->m_ajSoftwareVersion,
                            rt, access, member, request);
                    QStatus status = resource->MethodCallAsync(*member, resource,
                            static_cast<ajn::MessageReceiver::ReplyHandler>(&VirtualResource::MethodReturnCB),
                            &arg, 1, context, DefaultCallTimeout,
                            resource->GetMethodCallFlags(ifaceName.c_str()));
                    if (status == ER_OK)
                    {
                        result = OC_EH_OK;
                    }
                    else
                    {
                        LOG(LOG_ERR, "MethodCallAsync - %s", QCC_StatusText(status));
                        delete context;
                        result = OC_EH_ERROR;
                    }
                }
                else
                {
                    OCEntityHandlerResponse response;
                    memset(&response, 0, sizeof(response));
                    response.requestHandle = request->requestHandle;
                    response.resourceHandle = request->resource;
                    OCRepPayload *payload = resource->CreatePayload(uri);
                    if (resource->SetMemberPayload(payload, ifaceName.c_str(), memberName.c_str()) != OC_STACK_OK)
                    {
                        result = OC_EH_ERROR;
                        break;
                    }
                    result = OC_EH_OK;
                    response.ehResult = result;
                    response.payload = reinterpret_cast<OCPayload *>(payload);
                    OCStackResult doResult = OCDoResponse(&response);
                    if (doResult != OC_STACK_OK)
                    {
                        LOG(LOG_ERR, "OCDoResponse - %d", doResult);
                        OCRepPayloadDestroy(payload);
                    }
                }
                break;
            }
        case OC_REST_POST:
            {
                if ((access & READWRITE) == 0)
                {
                    LOG(LOG_INFO, "Read only access");
                    result = OC_EH_METHOD_NOT_ALLOWED;
                    break;
                }
                std::string memberName = GetMember(rt);
                if (memberName.empty() || memberName == "const" || memberName == "true" ||
                        memberName == "false" || memberName == "invalidates")
                {
                    if (!request->payload || request->payload->type != PAYLOAD_TYPE_REPRESENTATION)
                    {
                        LOG(LOG_INFO, "Missing or unexpected payload type: %d",
                                (request && request->payload) ? request->payload->type : PAYLOAD_TYPE_INVALID);
                        result = OC_EH_BAD_REQ;
                        break;
                    }
                    OCRepPayload *payload = (OCRepPayload *) request->payload;
                    if (!payload->values)
                    {
                        LOG(LOG_INFO, "Missing payload values");
                        result = OC_EH_BAD_REQ;
                        break;
                    }
                    SetContext *context = new SetContext(resource->m_ajSoftwareVersion, request);
                    QStatus status = resource->Set(context);
                    if (status == ER_OK)
                    {
                        result = OC_EH_OK;
                    }
                    else
                    {
                        LOG(LOG_ERR, "Set - %s", QCC_StatusText(status));
                        delete context;
                        result = OC_EH_ERROR;
                    }
                }
                else
                {
                    /*
                     * We don't implement mixing of multiple method calls in one POST request, the
                     * resource type must be specified.
                     */
                    std::string ifaceName = ::GetInterface(rt);
                    const ajn::InterfaceDescription *iface = resource->GetInterface(ifaceName.c_str());
                    if (!iface)
                    {
                        LOG(LOG_INFO, "No such interface %s", ifaceName.c_str());
                        result = OC_EH_BAD_REQ;
                        break;
                    }
                    const ajn::InterfaceDescription::Member *member = iface->GetMethod(memberName.c_str());
                    if (!member)
                    {
                        LOG(LOG_INFO, "No such member %s.%s", ifaceName.c_str(), memberName.c_str());
                        result = OC_EH_ERROR;
                        break;
                    }
                    bool success = true;
                    size_t numArgs = CountCompleteTypes(member->signature.c_str());
                    ajn::MsgArg *args = NULL;
                    if (numArgs)
                    {
                        args = new ajn::MsgArg[numArgs];
                        if (!request->payload || request->payload->type != PAYLOAD_TYPE_REPRESENTATION)
                        {
                            LOG(LOG_INFO, "Missing or unexpected payload type: %d",
                                    (request && request->payload) ? request->payload->type : PAYLOAD_TYPE_INVALID);
                            result = OC_EH_ERROR;
                            break;
                        }
                    }
                    qcc::String propName = GetPropName(member, "validity");
                    OCRepPayload *payload = (OCRepPayload *) request->payload;
                    if (payload)
                    {
                        for (OCRepPayloadValue *value = payload->values; value; value = value->next)
                        {
                            if (propName == value->name && (value->type != OCREP_PROP_BOOL || !value->b))
                            {
                                LOG(LOG_INFO, "Invalid %s", propName.c_str());
                                success = false;
                                break;
                            }
                        }
                    }
                    const char *signature = member->signature.c_str();
                    const char *argSignature = signature;
                    const char *argNames = member->argNames.c_str();
                    for (size_t i = 0; success && i < numArgs; ++i)
                    {
                        ParseCompleteType(signature);
                        qcc::String sig(argSignature, signature - argSignature);
                        argSignature = signature;
                        std::string argName = NextArgName(argNames);
                        if (resource->m_ajSoftwareVersion >= "v16.10.00")
                        {
                            member->GetArgAnnotation(argName.c_str(), "org.alljoyn.Bus.Type.Name", sig);
                        }
                        qcc::String propName = GetPropName(member, argName, i);
                        assert(payload);
                        for (OCRepPayloadValue *value = payload->values; value; value = value->next)
                        {
                            if (propName == value->name)
                            {
                                success = ToAJMsgArg(&args[i], sig.c_str(), value);
                                break;
                            }
                        }
                    }
                    if (success)
                    {
                        MethodCallContext *context = new MethodCallContext(resource->m_ajSoftwareVersion, rt, access,
                                member, request);
                        QStatus status = resource->MethodCallAsync(*member, resource,
                                static_cast<ajn::MessageReceiver::ReplyHandler>(&VirtualResource::MethodReturnCB),
                                args, numArgs, context);
                        if (status == ER_OK)
                        {
                            result = OC_EH_OK;
                        }
                        else
                        {
                            LOG(LOG_ERR, "MethodCallAsync - %s", QCC_StatusText(status));
                            delete context;
                            result = OC_EH_ERROR;
                        }
                    }
                    else
                    {
                        result = OC_EH_ERROR;
                    }
                    delete[] args;
                }
                break;
            }
        default:
            result = OC_EH_METHOD_NOT_ALLOWED;
            break;
    }
    return result;
}

void VirtualResource::MethodReturnCB(ajn::Message &msg, void *ctx)
{
    LOG(LOG_INFO, "[%p] ctx=%p", this, ctx);

    std::lock_guard<std::mutex> lock(m_mutex);
    MethodCallContext *context = reinterpret_cast<MethodCallContext *>(ctx);
    const char *uri = OCGetResourceUri(context->m_response->resourceHandle);
    OCStackResult result = OC_STACK_ERROR;
    OCPayload *payload = NULL;
    switch (msg->GetType())
    {
        case ajn::MESSAGE_METHOD_RET:
            payload = (OCPayload*) CreatePayload(uri);
            bool success;
            if (!strcmp(context->m_member->iface->GetName(),
                        ajn::org::freedesktop::DBus::Properties::InterfaceName) &&
                !strcmp(context->m_member->name.c_str(), "GetAll"))
            {
                const ajn::InterfaceDescription *iface =
                        m_bus->GetInterface(::GetInterface(context->m_rt).c_str());
                assert(iface);
                success = ToFilteredOCPayload((OCRepPayload *) payload, m_ajSoftwareVersion, iface,
                        GetMember(context->m_rt).c_str(), context->m_access, msg->GetArg(0));
            }
            else
            {
                size_t numInArgs = CountCompleteTypes(context->m_member->signature.c_str());
                size_t numOutArgs;
                const ajn::MsgArg *outArgs;
                msg->GetArgs(numOutArgs, outArgs);
                std::string propName = GetPropName(context->m_member, "validity");
                OCRepPayloadSetPropBool((OCRepPayload *) payload, propName.c_str(), true);
                const char *argNames = context->m_member->argNames.c_str();
                for (size_t i = 0; i < numInArgs; ++i)
                {
                    NextArgName(argNames);
                }
                success = true;
                const char *signature = context->m_member->returnSignature.c_str();
                const char *argSignature = signature;
                for (size_t i = 0; success && i < numOutArgs; ++i)
                {
                    ParseCompleteType(signature);
                    qcc::String sig(argSignature, signature - argSignature);
                    argSignature = signature;
                    std::string argName = NextArgName(argNames);
                    if (context->m_ajSoftwareVersion >= "v16.10.00")
                    {
                        context->m_member->GetArgAnnotation(argName.c_str(),
                                "org.alljoyn.Bus.Type.Name", sig);
                    }
                    propName = GetPropName(context->m_member, argName, numInArgs + i);
                    success = ToOCPayload((OCRepPayload *) payload, propName.c_str(),
                            GetPropType(context->m_member, argName.c_str(), &outArgs[i]),
                            &outArgs[i], sig.c_str());
                }
            }
            if (success)
            {
                context->m_response->ehResult = OC_EH_OK;
            }
            else
            {
                context->m_response->ehResult = OC_EH_ERROR;
                OCPayloadDestroy(payload);
                payload = NULL;
            }
            break;
        case ajn::MESSAGE_ERROR:
            payload = (OCPayload*) CreatePayload(msg, &context->m_response->ehResult);
            break;
        default:
            assert(0);
            break;
    }
    context->m_response->payload = payload;
    result = OCDoResponse(context->m_response);
    if (result != OC_STACK_OK)
    {
        LOG(LOG_ERR, "OCDoResponse - %d", result);
        OCPayloadDestroy(payload);
    }
    delete context;
}

/* Called with m_mutex held. */
QStatus VirtualResource::Set(SetContext *context)
{
    LOG(LOG_INFO, "[%p] context=%p name=%s", this, context, context->m_value->name);

    /*
     * OC value name may have '.' in the property name portion before translation.  This occurs when
     * the AllJoyn bus object has a property named e.g. "one_dtwo".  The loop below tries to locate
     * the interface component of names of this form.
     */
    const ajn::InterfaceDescription *iface = NULL;
    const ajn::InterfaceDescription::Property *property = NULL;
    std::string valueName = context->m_value->name;
    for (size_t pos = valueName.rfind('.'); pos != std::string::npos;
            pos = valueName.rfind('.', pos - 1))
    {
        std::string ifaceName = ToAJName(valueName.substr(0, pos));
        iface = GetInterface(ifaceName.c_str());
        if (!iface)
        {
            continue;
        }
        size_t dot = valueName.find('.', pos + 1);
        if (dot == std::string::npos)
        {
            continue;
        }
        std::string prefix = valueName.substr(pos + 1, dot - (pos + 1));
        std::string propName = valueName.substr(dot + 1);
        propName = ToAJPropName(propName);
        property = iface->GetProperty(propName.c_str());
        if (!property)
        {
            continue;
        }
        qcc::String emitsChangedValue = (property->name == "Version") ? "const" : "false";
        property->GetAnnotation(::ajn::org::freedesktop::DBus::AnnotateEmitsChanged, emitsChangedValue);
        if (emitsChangedValue != prefix)
        {
            property = NULL;
            continue;
        }
        break;
    }
    if (!iface)
    {
        return ER_BUS_NO_SUCH_INTERFACE;
    }
    if (!property)
    {
        return ER_BUS_NO_SUCH_PROPERTY;
    }
    if (property->access == ajn::PROP_ACCESS_READ)
    {
        return ER_BUS_PROPERTY_ACCESS_DENIED;
    }
    size_t numArgs = 3;
    ajn::MsgArg args[3];
    args[0].Set("s", iface->GetName());
    args[1].Set("s", property->name.c_str());
    qcc::String signature = property->signature;
    if (context->m_ajSoftwareVersion >= "v16.10.00")
    {
        property->GetAnnotation("org.alljoyn.Bus.Type.Name", signature);
    }
    ajn::MsgArg value;
    if (!ToAJMsgArg(&value, signature.c_str(), context->m_value))
    {
        return ER_FAIL;
    }
    args[2].Set("v", &value);
    return MethodCallAsync(::ajn::org::freedesktop::DBus::Properties::InterfaceName, "Set", this,
            static_cast<ajn::MessageReceiver::ReplyHandler>(&VirtualResource::SetCB), args, numArgs,
            context, DefaultCallTimeout, GetMethodCallFlags(iface->GetName()));
}

void VirtualResource::SetCB(ajn::Message &msg, void *ctx)
{
    LOG(LOG_INFO, "[%p] msg={type=%d},ctx=%p", this, msg->GetType(), ctx);

    std::lock_guard<std::mutex> lock(m_mutex);
    SetContext *context = reinterpret_cast<SetContext *>(ctx);
    const char *uri = OCGetResourceUri(context->m_response->resourceHandle);
    OCStackResult result = OC_STACK_ERROR;
    OCRepPayload *payload = NULL;
    switch (msg->GetType())
    {
        case ajn::MESSAGE_METHOD_RET:
            context->m_value = context->m_value->next;
            if (!context->m_value)
            {
                payload = CreatePayload(uri);
                context->m_response->ehResult = OC_EH_OK;
                context->m_response->payload = reinterpret_cast<OCPayload *>(payload);
                result = OCDoResponse(context->m_response);
                delete context;
                break;
            }
            else
            {
                QStatus status = Set(context);
                if (status == ER_OK)
                {
                    result = OC_STACK_OK;
                    break;
                }
            }
            /* FALLTHROUGH */
        case ajn::MESSAGE_ERROR:
            context->m_response->payload = (OCPayload *) CreatePayload(msg,
                    &context->m_response->ehResult);
            result = OCDoResponse(context->m_response);
            delete context;
            break;
        default:
            assert(0);
            break;
    }
    if (result != OC_STACK_OK)
    {
        LOG(LOG_ERR, "OCDoResponse - %d", result);
        OCRepPayloadDestroy(payload);
    }
}

struct VirtualResource::GetAllInvalidatedContext
{
    const ajn::InterfaceDescription *m_iface;
    GetAllInvalidatedContext(const ajn::InterfaceDescription *iface)
        : m_iface(iface) { }
};

void VirtualResource::SignalCB(const ajn::InterfaceDescription::Member *member, const char *path,
                               ajn::Message &msg)
{
    LOG(LOG_INFO, "[%p] member=%p,path=%s", this, member, path);

    std::lock_guard<std::mutex> lock(m_mutex);
    if (m_observers.empty())
    {
        LOG(LOG_INFO, "[%p] No observers", this);
        return;
    }
    if (!strcmp(msg->GetInterface(), ajn::org::freedesktop::DBus::Properties::InterfaceName) &&
        !strcmp(msg->GetMemberName(), "PropertiesChanged"))
    {
        const char *ifaceName = msg->GetArg(0)->v_string.str;
        const ajn::InterfaceDescription *iface = m_bus->GetInterface(ifaceName);
        assert(iface);
        if (msg->GetArg(2)->v_array.GetNumElements())
        {
            /* Get the values of the invalidated properties */
            GetAllInvalidatedContext *context = new GetAllInvalidatedContext(iface);
            QStatus status = MethodCallAsync(::ajn::org::freedesktop::DBus::Properties::InterfaceName,
                    "GetAll", this, static_cast<ajn::MessageReceiver::ReplyHandler>(&VirtualResource::GetAllInvalidatedCB),
                    msg->GetArg(0), 1, context, DefaultCallTimeout, GetMethodCallFlags(ifaceName));
            if (status != ER_OK)
            {
                LOG(LOG_ERR, "MethodCallAsync - %s", QCC_StatusText(status));
                delete context;
            }
        }
        else
        {
            const ajn::MsgArg *dict = msg->GetArg(1);
            NotifyPropertiesChangedObservers(iface, dict);
        }
    }
    else
    {
        std::string rt = GetResourceTypeName(msg->GetInterface(), msg->GetMemberName());
        for (std::map<Observation, std::vector<OCObservationId>>::iterator it = m_observers.begin();
             it != m_observers.end(); ++it)
        {
            std::map<std::string, std::string> queryMap = ParseQuery(it->first.m_resource,
                    it->first.m_query.c_str());
            std::string rtQuery = GetResourceType(it->first.m_resource, queryMap);
            if (!rtQuery.empty() && rtQuery != rt)
            {
                continue;
            }
            const char *uri = OCGetResourceUri(it->first.m_resource);
            const ajn::InterfaceDescription *iface = GetInterface(msg->GetInterface());
            assert(iface);
            const ajn::InterfaceDescription::Member *member = iface->GetMember(msg->GetMemberName());
            assert(member);
            const char *argNames = member->argNames.c_str();
            size_t numArgs;
            const ajn::MsgArg *args;
            msg->GetArgs(numArgs, args);
            std::string propName = GetPropName(member, "validity");
            OCRepPayload *payload = CreatePayload(uri);
            OCRepPayloadSetPropBool(payload, propName.c_str(), true);
            bool success = true;
            const char *signature = member->signature.c_str();
            const char *argSignature = signature;
            for (size_t i = 0; success && i < numArgs; ++i)
            {
                ParseCompleteType(signature);
                qcc::String sig(argSignature, signature - argSignature);
                argSignature = signature;
                std::string argName = NextArgName(argNames);
                if (m_ajSoftwareVersion >= "v16.10.00")
                {
                    member->GetArgAnnotation(argName.c_str(), "org.alljoyn.Bus.Type.Name", sig);
                }
                propName = GetPropName(member, argName, i);
                success = ToOCPayload(payload, propName.c_str(),
                        GetPropType(member, argName.c_str(), &args[i]), &args[i], sig.c_str());
            }
            if (success)
            {
                OCStackResult result = OCNotifyListOfObservers(it->first.m_resource, &it->second[0],
                        it->second.size(), payload, OC_HIGH_QOS);
                if (result == OC_STACK_OK)
                {
                    LOG(LOG_INFO, "[%p] Notify observers rt=%s", this, it->first.m_query.c_str());
                }
                else
                {
                    LOG(LOG_ERR, "[%p] Notify observers - %d", this, result);
                    OCRepPayloadDestroy(payload);
                }
            }
            else
            {
                OCRepPayloadDestroy(payload);
            }
        }
    }
}

void VirtualResource::GetAllInvalidatedCB(ajn::Message &msg, void *ctx)
{
    LOG(LOG_INFO, "[%p] ctx=%p", this, ctx);

    std::lock_guard<std::mutex> lock(m_mutex);
    GetAllInvalidatedContext *context = reinterpret_cast<GetAllInvalidatedContext *>(ctx);
    const ajn::MsgArg *dict = msg->GetArg(0);
    NotifyPropertiesChangedObservers(context->m_iface, dict);
    delete context;
}

void VirtualResource::NotifyPropertiesChangedObservers(const ajn::InterfaceDescription *iface,
        const ajn::MsgArg *dict)
{
    for (std::map<Observation, std::vector<OCObservationId>>::iterator it = m_observers.begin();
         it != m_observers.end(); ++it)
    {
        const char *uri = OCGetResourceUri(it->first.m_resource);
        OCRepPayload *payload = CreatePayload(uri);
        std::map<std::string, std::string> queryMap = ParseQuery(it->first.m_resource,
                it->first.m_query.c_str());
        std::string rt = GetResourceType(it->first.m_resource, queryMap);
        uint8_t access = GetAccess(queryMap);
        std::string memberName = GetMember(rt);
        bool success;
        if (memberName.empty())
        {
            success = ToFilteredOCPayload(payload, m_ajSoftwareVersion, iface, "true",
                    access, dict) &&
                    ToFilteredOCPayload(payload, m_ajSoftwareVersion, iface, "invalidates",
                            access, dict);
        }
        else
        {
            success = ToFilteredOCPayload(payload, m_ajSoftwareVersion, iface,
                    memberName.c_str(), access, dict);
        }
        if (success && payload->values)
        {
            OCStackResult result = OCNotifyListOfObservers(it->first.m_resource,
                    &it->second[0], it->second.size(), payload, OC_HIGH_QOS);
            if (result == OC_STACK_OK)
            {
                LOG(LOG_INFO, "[%p] Notify observers rt=%s", this, it->first.m_query.c_str());
            }
            else
            {
                LOG(LOG_ERR, "[%p] Notify observers - %d", this, result);
                OCRepPayloadDestroy(payload);
            }
        }
        else
        {
            OCRepPayloadDestroy(payload);
        }
    }
}

/* Called with m_mutex held. */
QStatus VirtualResource::GetAll(GetAllContext *context)
{
    LOG(LOG_INFO, "[%p] context=%p", this, context);

    for (; (context->m_iface < context->m_numIfaces)
         && (context->m_response->ehResult == OC_EH_OK); ++context->m_iface)
    {
        const char *ifaceName = context->m_ifaces[context->m_iface]->GetName();
        if (!TranslateInterface(ifaceName))
        {
            continue;
        }
        size_t numProps = context->m_ifaces[context->m_iface]->GetProperties(NULL, 0);
        if (numProps)
        {
            ajn::MsgArg arg("s", ifaceName);
            QStatus status = MethodCallAsync(::ajn::org::freedesktop::DBus::Properties::InterfaceName,
                    "GetAll", this, static_cast<ajn::MessageReceiver::ReplyHandler>(&VirtualResource::GetAllCB),
                    &arg, 1, context, DefaultCallTimeout, GetMethodCallFlags(ifaceName));
            if (status != ER_OK)
            {
                LOG(LOG_ERR, "MethodCallAsync - %s", QCC_StatusText(status));
                context->m_response->ehResult = OC_EH_ERROR;
            }
            break;
        }
    }
    if ((context->m_response->ehResult != OC_EH_OK) || (context->m_iface == context->m_numIfaces))
    {
        if (context->m_response->ehResult == OC_EH_OK)
        {
            bool observable = OCGetResourceProperties(context->m_response->resourceHandle) &
                    OC_OBSERVABLE;
            for (size_t i = 0; (i < context->m_numIfaces) && (context->m_response->ehResult == OC_EH_OK); ++i)
            {
                const char *ifaceName = context->m_ifaces[i]->GetName();
                if (!TranslateInterface(ifaceName))
                {
                    continue;
                }
                size_t numMembers = context->m_ifaces[i]->GetMembers(NULL, 0);
                const ajn::InterfaceDescription::Member **members = new const
                ajn::InterfaceDescription::Member*[numMembers];
                context->m_ifaces[i]->GetMembers(members, numMembers);
                for (size_t j = 0; (j < numMembers) && (context->m_response->ehResult == OC_EH_OK); ++j)
                {
                    if ((observable && (members[j]->memberType == ajn::MESSAGE_SIGNAL)) ||
                            (!observable && (members[j]->memberType == ajn::MESSAGE_METHOD_CALL)))
                    {
                        if (SetMemberPayload(context->m_payload, ifaceName, members[j]->name.c_str()) != OC_STACK_OK)
                        {
                            context->m_response->ehResult = OC_EH_ERROR;
                        }
                    }
                }
                delete[] members;
            }
        }
        /* Common properties */
        if (context->m_response->ehResult == OC_EH_OK)
        {
            if (!SetResourceTypes(context->m_payload, context->m_response->resourceHandle) ||
                    !SetInterfaces(context->m_payload, context->m_response->resourceHandle))
            {
                context->m_response->ehResult = OC_EH_ERROR;
                goto exit;
            }
        }
exit:
        if (context->m_response->ehResult == OC_EH_OK)
        {
            context->m_response->payload = reinterpret_cast<OCPayload *>(context->m_payload);
        }
        OCStackResult doResult = OCDoResponse(context->m_response);
        if (doResult != OC_STACK_OK)
        {
            LOG(LOG_ERR, "OCDoResponse - %d", doResult);
        }
        delete context;
    }
    return ER_OK;
}

void VirtualResource::GetAllCB(ajn::Message &msg, void *ctx)
{
    LOG(LOG_INFO, "[%p] ctx=%p", this, ctx);

    std::lock_guard<std::mutex> lock(m_mutex);
    GetAllContext *context = reinterpret_cast<GetAllContext *>(ctx);
    switch (msg->GetType())
    {
        case ajn::MESSAGE_METHOD_RET:
            {
                const ajn::InterfaceDescription *iface = context->m_ifaces[context->m_iface];
                const ajn::MsgArg *dict = msg->GetArg(0);
                bool success = true;
                if (OCGetResourceProperties(context->m_response->resourceHandle) & OC_OBSERVABLE)
                {
                    success = ToFilteredOCPayload(context->m_payload, context->m_ajSoftwareVersion,
                            iface, "true", context->m_access, dict) &&
                            ToFilteredOCPayload(context->m_payload, context->m_ajSoftwareVersion,
                                    iface, "invalidates", context->m_access, dict);
                }
                else
                {
                    success = ToFilteredOCPayload(context->m_payload, context->m_ajSoftwareVersion,
                            iface, "const", context->m_access, dict) &&
                            ToFilteredOCPayload(context->m_payload, context->m_ajSoftwareVersion,
                                    iface, "false", context->m_access, dict);
                }
                if (success)
                {
                    context->m_response->ehResult = OC_EH_OK;
                }
                else
                {
                    context->m_response->ehResult = OC_EH_ERROR;
                }
                break;
            }
        case ajn::MESSAGE_ERROR:
            context->m_response->payload = (OCPayload *) CreatePayload(msg,
                    &context->m_response->ehResult);
            break;
        default:
            assert(0);
            break;
    }
    ++context->m_iface;
    QStatus status = GetAll(context);
    if (status != ER_OK)
    {
        LOG(LOG_ERR, "GetAll - %s", QCC_StatusText(status));
        delete context;
    }
}

void VirtualResource::AddMatchCB(QStatus status, void *ctx)
{
    (void) ctx;
    if (status != ER_OK)
    {
        LOG(LOG_ERR, "AddMatchCB - %s", QCC_StatusText(status));
    }
}

void VirtualResource::RemoveMatchCB(QStatus status, void *ctx)
{
    (void) ctx;
    if (status != ER_OK)
    {
        LOG(LOG_ERR, "RemoveMatchCB - %s", QCC_StatusText(status));
    }
}

uint8_t VirtualResource::GetMethodCallFlags(const char *ifaceName)
{
    uint8_t flags = 0;
    const ajn::InterfaceDescription *iface = m_bus->GetInterface(ifaceName);
    if (iface)
    {
        ajn::InterfaceSecurityPolicy security = iface->GetSecurityPolicy();
        if ((security == ajn::AJ_IFC_SECURITY_REQUIRED) ||
                (IsSecure() && (security != ajn::AJ_IFC_SECURITY_OFF)))
        {
            flags |= ajn::ALLJOYN_FLAG_ENCRYPTED;
        }
    }
    return flags;
}


text:
package com.rackspacecloud.blueflood.io.datastax;

import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.ResultSetFuture;
import com.rackspacecloud.blueflood.io.serializers.metrics.RawSerDes;
import com.rackspacecloud.blueflood.rollup.Granularity;
import com.rackspacecloud.blueflood.types.IMetric;

import java.nio.ByteBuffer;

/**
 * This class holds the utility methods to read/write simple numbers
 * using Datastax driver. This is mostly used during Ingest and metrics
 * are inserted to the metrics_full Column Family
 */
public class DSimpleNumberIO extends DAbstractMetricIO {

    private RawSerDes serDes = new RawSerDes();

    @Override
    protected ByteBuffer toByteBuffer( Object value ) {

        return serDes.serialize( value );
    }

    @Override
    protected Object fromByteBuffer( ByteBuffer byteBuffer ) {

        return serDes.deserialize( byteBuffer );
    }

    /**
     * Inserts a raw metric (not its rolled up value) to the proper
     * column family
     *
     * @param metric
     * @return
     */
    public ResultSetFuture insertRawAsync( IMetric metric ) {

        BoundStatement bound = getBoundStatementForMetric(metric);
        return session.executeAsync(bound);

    }

    /**
     * Constructs a {@link BoundStatement} for a particular metric.
     * The statement could be part of a BatchStatement or it could
     * be executed as is.
     *
     * @param metric
     * @return
     */
    public BoundStatement getBoundStatementForMetric(IMetric metric) {
        return metricsCFPreparedStatements.insertToMetricsBasicFullStatement.bind(
                metric.getLocator().toString(),
                metric.getCollectionTime(),
                serDes.serialize( metric.getMetricValue() ),
                metric.getTtlInSeconds() );
    }

    @Override
    protected BoundStatement getBoundStatementForMetric(IMetric metric, Granularity granularity) {
        // we ignore granularity from the abstract parent because
        // this class is only used to write to metrics_full
        return getBoundStatementForMetric(metric);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.sakaiproject.evaluation.tool.reporting;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import org.sakaiproject.evaluation.constant.EvalConstants;
import org.sakaiproject.evaluation.logic.EvalCommonLogic;
import org.sakaiproject.evaluation.logic.model.EvalUser;
import org.sakaiproject.evaluation.model.EvalAnswer;
import org.sakaiproject.evaluation.model.EvalEvaluation;
import org.sakaiproject.evaluation.tool.utils.EvalResponseAggregatorUtil;
import org.sakaiproject.evaluation.utils.EvalUtils;
import org.sakaiproject.evaluation.utils.TemplateItemDataList;
import org.sakaiproject.evaluation.utils.TemplateItemDataList.DataTemplateItem;

import uk.org.ponder.messageutil.MessageLocator;
import uk.org.ponder.util.UniversalRuntimeException;
import au.com.bytecode.opencsv.CSVWriter;

/**
 *
 * @author Steven Githens
 * @author Aaron Zeckoski (aaronz@vt.edu)
 */
public class CSVReportExporter implements ReportExporter {

    private static final char COMMA = ',';

    private EvalCommonLogic commonLogic;
    public void setCommonLogic(EvalCommonLogic commonLogic) {
        this.commonLogic = commonLogic;
    }

    private EvalResponseAggregatorUtil responseAggregator;
    public void setEvalResponseAggregatorUtil(EvalResponseAggregatorUtil bean) {
        this.responseAggregator = bean;
    }

    private MessageLocator messageLocator;
    public void setMessageLocator(MessageLocator locator) {
        this.messageLocator = locator;
    }

    /* (non-Javadoc)
     * @see org.sakaiproject.evaluation.tool.reporting.ReportExporter#buildReport(org.sakaiproject.evaluation.model.EvalEvaluation, java.lang.String[], java.io.OutputStream)
     */
    public void buildReport(EvalEvaluation evaluation, String[] groupIds, OutputStream outputStream) {
        buildReport(evaluation, groupIds, null, outputStream);
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.sakaiproject.evaluation.tool.reporting.ReportExporter#buildReport(org.sakaiproject.evaluation
     * .model.EvalEvaluation, java.lang.String[], java.lang.String, java.io.OutputStream)
     */
    public void buildReport(EvalEvaluation evaluation, String[] groupIds, String evaluateeId, OutputStream outputStream) {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
        CSVWriter writer = new CSVWriter(outputStreamWriter, COMMA);

        Boolean instructorViewAllResults = (boolean) evaluation.getInstructorViewAllResults();
        String currentUserId = commonLogic.getCurrentUserId();
        String evalOwner = evaluation.getOwner();

        boolean isCurrentUserAdmin = commonLogic.isUserAdmin(currentUserId);

        // 1 Make TIDL
        TemplateItemDataList tidl = responseAggregator.prepareTemplateItemDataStructure(evaluation.getId(), groupIds);

        // 2 get DTIs for this eval from tidl
        List<DataTemplateItem> dtiList = tidl.getFlatListOfDataTemplateItems(true);

        // 3 use DTIs to make the headers
        List<String> questionCatRow = new ArrayList<String>();
        List<String> questionTypeRow = new ArrayList<String>();
        List<String> questionTextRow = new ArrayList<String>();
        for (DataTemplateItem dti : dtiList) {

            if (!instructorViewAllResults // If the eval is so configured,
              && !isCurrentUserAdmin // and currentUser is not an admin
              && !currentUserId.equals(evalOwner) // and currentUser is not the eval creator
              && !EvalConstants.ITEM_CATEGORY_COURSE.equals(dti.associateType)
              && !currentUserId.equals(commonLogic.getEvalUserById(dti.associateId).userId) ) {
                //skip instructor items that aren't for the current user
                continue;
            }

            questionTypeRow.add(responseAggregator.getHeaderLabelForItemType(dti.getTemplateItemType()));
            questionTextRow.add(commonLogic.makePlainTextFromHTML(dti.templateItem.getItem().getItemText()));
            if (EvalConstants.ITEM_CATEGORY_INSTRUCTOR.equals(dti.associateType)) {
                EvalUser user = commonLogic.getEvalUserById( dti.associateId );
                String instructorMsg = messageLocator.getMessage("reporting.spreadsheet.instructor",
                        new Object[] {user.displayName} );
                questionCatRow.add( instructorMsg );
            } else if (EvalConstants.ITEM_CATEGORY_ASSISTANT.equals(dti.associateType)) {
                EvalUser user = commonLogic.getEvalUserById( dti.associateId );
                String assistantMsg = messageLocator.getMessage("reporting.spreadsheet.ta",
                        new Object[] {user.displayName} );
                questionCatRow.add( assistantMsg );
            } else if (EvalConstants.ITEM_CATEGORY_COURSE.equals(dti.associateType)) {
                questionCatRow.add(messageLocator.getMessage("reporting.spreadsheet.course"));
            } else {
                questionCatRow.add(messageLocator.getMessage("unknown.caps"));
            }

            if (dti.usesComments()) {
                // add an extra column for comments
                questionTypeRow.add(messageLocator.getMessage("viewreport.comments.header"));
                // also add in blanks for the other columns
                questionTextRow.add("");
                questionCatRow.add("");
            }

        }

        writer.writeNext(questionCatRow.toArray(new String[] {}));
        writer.writeNext(questionTypeRow.toArray(new String[] {}));
        writer.writeNext(questionTextRow.toArray(new String[] {}));

        // 4) get responseIds from tidl
        List<Long> responseIds = tidl.getResponseIdsForAnswers();

        // 5) loop over response ids
        for (Long responseId : responseIds) {
            // 6) loop over DTIs
            List<String> nextResponseRow = new ArrayList<String>();
            for (DataTemplateItem dti : dtiList) {

                if (!instructorViewAllResults // If the eval is so configured,
                  && !isCurrentUserAdmin // and currentUser is not an admin
                  && !currentUserId.equals(evalOwner) // and currentUser is not the eval creator
                  && !EvalConstants.ITEM_CATEGORY_COURSE.equals(dti.associateType)
                  && !currentUserId.equals(commonLogic.getEvalUserById(dti.associateId).userId) ) {
                    //skip instructor items that aren't for the current user
                    continue;
                }

                EvalAnswer answer = dti.getAnswer(responseId);
                if (answer != null) {
                    nextResponseRow.add(responseAggregator.formatForSpreadSheet(answer.getTemplateItem(), answer));
                    if (dti.usesComments()) {
                        // put comment in the next column
                        nextResponseRow.add(EvalUtils.isBlank(answer.getComment()) ? "" : answer.getComment());
                    }
                } else {
                    nextResponseRow.add("");
                    if (dti.usesComments()) {
                        nextResponseRow.add(""); // put in blank to space columns correctly
                    }
                }
            }
            writer.writeNext(nextResponseRow.toArray(new String[] {}));
        }

        // convert the top row to an array
        /*
         * String[] topRowArray = new String[responses.topRow.size()]; for (int i = 0; i <
         * responses.topRow.size(); i++) { String questionString =
         * commonLogic.cleanupUserStrings(responses.topRow.get(i)); topRowArray[i] = (String)
         * questionString; } //write the top row to CSVWriter object writer.writeNext(topRowArray);
         *
         * //for each response for (int i = 0; i < responses.numOfResponses; i++) { List currRow =
         * (List) responses.responseRows.get(i); //convert the current response to an array String[]
         * currRowArray = new String[currRow.size()]; for (int j = 0; j < currRow.size(); j++) {
         * currRowArray[j] = (String) currRow.get(j); } //writer the current response to CSVWriter
         * object writer.writeNext(currRowArray); }
         */

        try {
            writer.close();
        } catch (IOException e1) {
            throw UniversalRuntimeException.accumulate(e1, "Could not close the CSVWriter");
        }
    }

    public String getContentType() {
        return "text/csv";
    }
}


text:
using System;
using System.Runtime.InteropServices;

namespace Moritz.Globals.IODevices
{
    /// <summary>
    /// Describes the capabilities of a MIDI output device.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    internal struct MIDIOUTCAPS
    {
        /// <summary>
        /// Manufacturer identifier of the device driver for the MIDI output device.
        /// </summary>
        public UInt16 wMid;
        /// <summary>
        /// Product identifier of the MIDI output device.
        /// </summary>
        public UInt16 wPid;
        /// <summary>
        /// Version number of the device driver for the MIDI output device.
        /// The high-order byte is the major version number, and the low-order byte is the minor version number.
        /// </summary>
        public UInt32 vDriverVersion;
        /// <summary>
        /// Product name in a null-terminated string.
        /// </summary>
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Constants.MAXPNAMELEN)]
        public string szPname;
        /// <summary>
        /// Type of the MIDI output device.
        /// </summary>
        public UInt16 wTechnology;
        /// <summary>
        /// Number of voices supported by an internal synthesizer device.
        /// If the device is a port, this member is not meaningful and is set to 0.
        /// </summary>
        public UInt16 wVoices;
        /// <summary>
        /// Maximum number of simultaneous notes that can be played by an internal synthesizer device.
        /// If the device is a port, this member is not meaningful and is set to 0.
        /// </summary>
        public UInt16 wNotes;
        /// <summary>
        /// Channels that an internal synthesizer device responds to, where the least significant bit refers to channel 0 and the most significant bit to channel 15.
        /// </summary>
        public UInt16 wChannelMask;
        /// <summary>
        /// Optional functionality supported by the device.
        /// </summary>
        public UInt32 dwSupport;
    }

    /********************************************************************/
    /*
     * Below here added by j.i. May 2009
     *
     */

    /// <summary>
    /// Describes the capabilities of a MIDI input device. See http://msdn.microsoft.com/en-us/library/ms711596(VS.85).aspx
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    internal struct MIDIINCAPS
    {
        /// <summary>
        /// Manufacturer identifier of the device driver for the MIDI output device.
        /// </summary>
        public UInt16 wMid;
        /// <summary>
        /// Product identifier of the MIDI output device.
        /// </summary>
        public UInt16 wPid;
        /// <summary>
        /// Version number of the device driver for the MIDI input device.
        /// The high-order byte is the major version number, and the low-order byte is the minor version number.
        /// </summary>
        public UInt32 vDriverVersion;
        /// <summary>
        /// Product name in a null-terminated string.
        /// </summary>
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Constants.MAXPNAMELEN)]
        public string szPname;
        /// <summary>
        /// Optional functionality supported by the device.
        /// </summary>
        public UInt32 dwSupport;
    }
}


text:
namespace gl {
class SurfaceTexture;
}

namespace media {

class AVDACodecImage;

// Shared state to allow communication between the AVDA and the
// GLImages that configure GL for drawing the frames.
class AVDASharedState : public base::RefCounted<AVDASharedState> {
 public:
  AVDASharedState();

  GLuint surface_texture_service_id() const {
    return surface_texture_service_id_;
  }

  // Signal the "frame available" event.  This may be called from any thread.
  void SignalFrameAvailable();

  void WaitForFrameAvailable();

  void SetSurfaceTexture(scoped_refptr<gl::SurfaceTexture> surface_texture,
                         GLuint attached_service_id);

  // Context and surface that |surface_texture_| is bound to, if
  // |surface_texture_| is not null.
  gl::GLContext* context() const { return context_.get(); }

  gl::GLSurface* surface() const { return surface_.get(); }

  // Helper method for coordinating the interactions between
  // MediaCodec::ReleaseOutputBuffer() and WaitForFrameAvailable() when
  // rendering to a SurfaceTexture; this method should never be called when
  // rendering to a SurfaceView.
  //
  // The release of the codec buffer to the surface texture is asynchronous, by
  // using this helper we can attempt to let this process complete in a non
  // blocking fashion before the SurfaceTexture is used.
  //
  // Clients should call this method to release the codec buffer for rendering
  // and then call WaitForFrameAvailable() before using the SurfaceTexture. In
  // the ideal case the SurfaceTexture has already been updated, otherwise the
  // method will wait for a pro-rated amount of time based on elapsed time up
  // to a short deadline.
  //
  // Some devices do not reliably notify frame availability, so we use a very
  // short deadline of only a few milliseconds to avoid indefinite stalls.
  void RenderCodecBufferToSurfaceTexture(MediaCodecBridge* codec,
                                         int codec_buffer_index);

  // Helper methods for interacting with |surface_texture_|. See
  // gfx::SurfaceTexture for method details.
  void UpdateTexImage();
  // Returns a matrix that needs to be y flipped in order to match the
  // StreamTextureMatrix contract. See GLStreamTextureImage::YInvertMatrix().
  void GetTransformMatrix(float matrix[16]) const;

  // Resets the last time for RenderCodecBufferToSurfaceTexture(). Should be
  // called during codec changes.
  void clear_release_time() { release_time_ = base::TimeTicks(); }

 protected:
  virtual ~AVDASharedState();

 private:
  friend class base::RefCounted<AVDASharedState>;

  scoped_refptr<gl::SurfaceTexture> surface_texture_;

  // Platform gl texture id for |surface_texture_|.
  GLuint surface_texture_service_id_;

  // For signalling OnFrameAvailable().
  base::WaitableEvent frame_available_event_;

  // Context and surface that |surface_texture_| is bound to, if
  // |surface_texture_| is not null.
  scoped_refptr<gl::GLContext> context_;
  scoped_refptr<gl::GLSurface> surface_;

  // The time of the last call to RenderCodecBufferToSurfaceTexture(), null if
  // if there has been no last call or WaitForFrameAvailable() has been called
  // since the last call.
  base::TimeTicks release_time_;

  // Texture matrix of the front buffer of the surface texture.
  float gl_matrix_[16];

  class OnFrameAvailableHandler;
  scoped_refptr<OnFrameAvailableHandler> on_frame_available_handler_;

  DISALLOW_COPY_AND_ASSIGN(AVDASharedState);
};

}  // namespace media

#endif  // MEDIA_GPU_AVDA_SHARED_STATE_H_


text:
title: MySqlDataReader.HasRows property
---

# MySqlDataReader.HasRows property

```csharp
public override bool HasRows { get; }
```

## See Also

* class [MySqlDataReader](../../MySqlDataReaderType/)
* namespace [MySqlConnector](../../MySqlDataReaderType/)
* assembly [MySqlConnector](../../../MySqlConnectorAssembly/)

<!-- DO NOT EDIT: generated by xmldocmd for MySqlConnector.dll -->


text:
layout:     post
title:      Перископ
date:       2015-11-06
categories: app
---

[Periscope](https://www.periscope.tv/) - приложение, которое позволяет вести онлайн трансляцию со своего телефона.

Другие люди могут подключиться к трансляции и общаться с ведущим с помощью чата. Это похоже на всем известный чатрулет, но не совсем, ведь здесь видно только одного собеседника.

Начать трансляцию можно одним нажатием кнопки, прощай сложный в настройке youtube! Прощай запись своих вебинаров, а затем долгая загрузка их обратно в интернет. Periscope сохранит все ваши трансляции.

![](/images/per-br.png)

## Немного цифр

Через 10 дней после запуска у Periscope был уже 1 миллион пользователей. А через месяц после запуска твитер покупает его за 100 млн долларов. Такому сногсшибательному росту можно только позавидовать. А диванные аналитики говорили, что - "интернет уже не тот... взрывного роста уже не будет.. рынок охладел...".
А вот на тебе сначала - Убер и теперь Перископ!

На главном экране приложения карта, на которой можно выбрать трансляцию с любого уголка планеты. И смотреть например, рассвет в Бразилии, или бэкстейдж с концерта. Или смотреть трансляции пользователей, на которых подписан. Если ваш друг начал трансляцию - то тебе обязательно придет уведомление.

![](/images/per-mappng.png)

Пользователи онлайн подключаются к вашей трансляции и комментируют онлайн. Вы видите комментарии в нижней части экрана вместе с видео.

![](/images/per-vi.png)

Отдельный респект разработчикам приложения. Ведь с такой скоростью роста количества пользователей молодые приложения часто "выбывают из гонки", становятся недоступными из-за огромного количества новых пользователей и не подготовленной к нагрузке инфраструктуры. Чувствуется поддержка сильного twitter'а за спиной.


text:
class Notification(object):

    STARTUP           = "startup"
    SHOW_DIALOG       = "showDialog"
    HELLO             = "hello"

    # Menu
    MENU_FILE_OPEN      = "menuFileOpen"
    MENU_FILE_SAVEAS    = "menuFileSaveAs"
    MENU_FILE_PREFS     = "menuFilePreferences"
    MENU_VIEW_EDIT      = "menuViewEdit"
    MENU_VIEW_SUM       = "menuViewSummary"
    MENU_HELP_CONTENTS  = "menuHelpContents"
    MENU_HELP_ABOUT     = "menuHelpAbout"

    FILE_LOADED         = "fileLoaded"
    EDIT_SELECTED       = "editMode"
    SUM_SELECTED        = "summaryMode"

    # Date picker
    DISPLAY_DAY         = "displayDay"
    PREV_DAY            = "previousDay"
    NEXT_DAY            = "nextDay"
    PREV_WEEK           = "previousWeek"
    NEXT_WEEK           = "nextWeek"
    DATE_SELECTED       = "dateSelected"

    # Time Grid
    CELL_SELECTED       = "cellSelected"
    CELL_UPDATED        = "cellUpdated"


text:
package org.sufficientlysecure.rootcommands;

import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.Context;
import android.location.LocationManager;
import android.os.PowerManager;
import android.provider.Settings;

/**
 * This methods work when the apk is installed as a system app (under /system/app)
 */
public class SystemCommands {
    Context context;

    public SystemCommands(Context context) {
        super();
        this.context = context;
    }

    /**
     * Get GPS status
     *
     * @return
     */
    public boolean getGPS() {
        return ((LocationManager) context.getSystemService(Context.LOCATION_SERVICE))
                .isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    /**
     * Enable/Disable GPS
     *
     * @param value
     */
    @TargetApi(8)
    public void setGPS(boolean value) {
        ContentResolver localContentResolver = context.getContentResolver();
        Settings.Secure.setLocationProviderEnabled(localContentResolver,
                LocationManager.GPS_PROVIDER, value);
    }

    /**
     * TODO: Not ready yet
     */
    @TargetApi(8)
    public void reboot() {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        pm.reboot("recovery");
        pm.reboot(null);

        // not working:
        // reboot(null);
    }

    /**
     * Reboot the device immediately, passing 'reason' (may be null) to the underlying __reboot
     * system call. Should not return.
     *
     * Taken from com.android.server.PowerManagerService.reboot
     */
    // public void reboot(String reason) {
    //
    // // final String finalReason = reason;
    // Runnable runnable = new Runnable() {
    // public void run() {
    // synchronized (this) {
    // // ShutdownThread.reboot(mContext, finalReason, false);
    // try {
    // Class<?> clazz = Class.forName("com.android.internal.app.ShutdownThread");
    //
    // // if (mReboot) {
    // Method method = clazz.getMethod("reboot", Context.class, String.class,
    // Boolean.TYPE);
    // method.invoke(null, context, null, false);
    //
    // // if (mReboot) {
    // // Method method = clazz.getMethod("reboot", Context.class, String.class,
    // // Boolean.TYPE);
    // // method.invoke(null, mContext, mReason, mConfirm);
    // // } else {
    // // Method method = clazz.getMethod("shutdown", Context.class, Boolean.TYPE);
    // // method.invoke(null, mContext, mConfirm);
    // // }
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // }
    //
    // }
    // };
    // // ShutdownThread must run on a looper capable of displaying the UI.
    // mHandler.post(runnable);
    //
    // // PowerManager.reboot() is documented not to return so just wait for the inevitable.
    // // synchronized (runnable) {
    // // while (true) {
    // // try {
    // // runnable.wait();
    // // } catch (InterruptedException e) {
    // // }
    // // }
    // // }
    // }

}


text:
package org.apache.flink.runtime.executiongraph.metrics;

import org.apache.flink.metrics.Gauge;
import org.apache.flink.runtime.executiongraph.ExecutionGraph;
import org.apache.flink.runtime.jobgraph.JobStatus;

import static org.apache.flink.util.Preconditions.checkNotNull;

/**
 * A gauge that returns (in milliseconds) how long a job has not been not running any
 * more, in case it is in a failing/recovering situation. Running jobs return naturally
 * a value of zero.
 *
 * <p>For jobs that have never run (new not yet scheduled jobs), this gauge returns
 * {@value NOT_YET_RUNNING}, and for jobs that are not running any more, it returns
 * {@value NO_LONGER_RUNNING}.
 */
public class DownTimeGauge implements Gauge<Long> {

	public static final String METRIC_NAME = "downtime";

	private static final long NOT_YET_RUNNING = 0L;

	private static final long NO_LONGER_RUNNING = -1L;

	// ------------------------------------------------------------------------

	private final ExecutionGraph eg;

	public DownTimeGauge(ExecutionGraph executionGraph) {
		this.eg = checkNotNull(executionGraph);
	}

	// ------------------------------------------------------------------------

	@Override
	public Long getValue() {
		final JobStatus status = eg.getState();

		if (status == JobStatus.RUNNING) {
			// running right now - no downtime
			return 0L;
		}
		else if (status.isTerminalState()) {
			// not running any more -> finished or not on leader
			return NO_LONGER_RUNNING;
		}
		else {
			final long runningTimestamp = eg.getStatusTimestamp(JobStatus.RUNNING);
			if (runningTimestamp > 0) {
				// job was running at some point and is not running now
				// we use 'Math.max' here to avoid negative timestamps when clocks change
				return Math.max(System.currentTimeMillis() - runningTimestamp, 0);
			}
			else {
				// job was never scheduled so far
				return NOT_YET_RUNNING;
			}
		}
	}
}


text:
import netaddr
from tempest.lib import exceptions as lib_exc
from tempest import test

from neutron.common import constants
from neutron.tests.api import base
from neutron.tests.tempest import config

CONF = config.CONF

class NetworksTestDHCPv6(base.BaseNetworkTest):
    _ip_version = 6

    @classmethod
    def skip_checks(cls):
        msg = None
        if not CONF.network_feature_enabled.ipv6:
            msg = "IPv6 is not enabled"
        elif not CONF.network_feature_enabled.ipv6_subnet_attributes:
            msg = "DHCPv6 attributes are not enabled."
        if msg:
            raise cls.skipException(msg)

    @classmethod
    def resource_setup(cls):
        super(NetworksTestDHCPv6, cls).resource_setup()
        cls.network = cls.create_network()

    def _remove_from_list_by_index(self, things_list, elem):
        for index, i in enumerate(things_list):
            if i['id'] == elem['id']:
                break
        del things_list[index]

    def _clean_network(self):
        body = self.client.list_ports()
        ports = body['ports']
        for port in ports:
            if (port['device_owner'].startswith(
                    constants.DEVICE_OWNER_ROUTER_INTF)
                and port['device_id'] in [r['id'] for r in self.routers]):
                self.client.remove_router_interface_with_port_id(
                    port['device_id'], port['id']
                )
            else:
                if port['id'] in [p['id'] for p in self.ports]:
                    self.client.delete_port(port['id'])
                    self._remove_from_list_by_index(self.ports, port)
        body = self.client.list_subnets()
        subnets = body['subnets']
        for subnet in subnets:
            if subnet['id'] in [s['id'] for s in self.subnets]:
                self.client.delete_subnet(subnet['id'])
                self._remove_from_list_by_index(self.subnets, subnet)
        body = self.client.list_routers()
        routers = body['routers']
        for router in routers:
            if router['id'] in [r['id'] for r in self.routers]:
                self.client.delete_router(router['id'])
                self._remove_from_list_by_index(self.routers, router)

    @test.idempotent_id('98244d88-d990-4570-91d4-6b25d70d08af')
    def test_dhcp_stateful_fixedips_outrange(self):
        """When port gets IP address from fixed IP range it
        shall be checked if it's from subnets range.
        """
        kwargs = {'ipv6_ra_mode': 'dhcpv6-stateful',
                  'ipv6_address_mode': 'dhcpv6-stateful'}
        subnet = self.create_subnet(self.network, **kwargs)
        ip_range = netaddr.IPRange(subnet["allocation_pools"][0]["start"],
                                   subnet["allocation_pools"][0]["end"])
        for i in range(1, 3):
            ip = netaddr.IPAddress(ip_range.last + i).format()
            self.assertRaises(lib_exc.BadRequest,
                              self.create_port,
                              self.network,
                              fixed_ips=[{'subnet_id': subnet['id'],
                                          'ip_address': ip}])

    def tearDown(self):
        self._clean_network()
        super(NetworksTestDHCPv6, self).tearDown()


text:
using System;
using HeyStack.Api.Server.Services;
using HeyStack.ServiceModel.Status;
using Moq;
using Shouldly;

namespace HeyStack.Api.Server.UnitTests {
    public class LocalApiWrapper : IWrapYourApi {

        private StatusService service;
        public StatusResultDto GetStatus() {
            return (service.Get(new GetStatusDto()));
        }

        public void Init() {
            var mockHost = new Mock<IHost>();
            mockHost.Setup(h => h.MachineName).Returns("TESTHOST");
            var mockClock = new Mock<IClock>();
            mockClock.Setup(clock => clock.Now).Returns(DateTime.MinValue);
            service = new StatusService(mockHost.Object, mockClock.Object);

        }

        public void TearDown() { }
    }
}


text:
Based on https://github.com/city41/breakouts, however the implementation guidelines make it clear that
this repo doesn't qualify as it's not pure javascript.

entitas init breakout
entitas create -c Animation animation:any
entitas create -c Body body:any
entitas create -c Sprite object:any
entitas create -c Stats lives:number score:number level:number
entitas create -c Ball
entitas create -c Block
entitas create -c Counter
entitas create -c Paddle
entitas create -c Player
entitas create -c WallLeft
entitas create -c WallRight
entitas create -c WallTop
entitas create -e Ball
entitas create -e Block
entitas create -e Counter
entitas create -e Paddle
entitas create -e Player
entitas create -e WallLeft
entitas create -e WallRight
entitas create -e WallTop
entitas create -s AddViewSystem ISetPool IInitializeSystem IExecuteSystem
entitas create -s AnimationUpdater ISetPool IInitializeSystem IExecuteSystem
entitas create -s BallDeathChecker ISetPool IInitializeSystem IExecuteSystem
entitas create -s BlockHit ISetPool IInitializeSystem IExecuteSystem
entitas create -s CountdownSystem ISetPool IInitializeSystem IExecuteSystem
entitas create -s DestroySystem ISetPool IInitializeSystem IExecuteSystem
entitas create -s InitializedLevel ISetPool IInitializeSystem IExecuteSystem
entitas create -s LevelChanger ISetPool IInitializeSystem IExecuteSystem
entitas create -s PaddleHit ISetPool IInitializeSystem IExecuteSystem
entitas create -s PaddleMovement ISetPool IInitializeSystem IExecuteSystem
entitas create -s PhysicsStep ISetPool IInitializeSystem IExecuteSystem
entitas create -s Renderer ISetPool IInitializeSystem IExecuteSystem
entitas create -s SpriteBodyUpdated ISetPool IInitializeSystem IExecuteSystem
entitas create -x Pool createPlayer:Entity
entitas create -x Pool createPaddle:Entity
entitas create -x Pool createWallTop:Entity
entitas create -x Pool createWallLeft:Entity
entitas create -x Pool createWallRight:Entity
entitas generate

# MIT License

Copyright (c) 2015 Bruce Davidson <darkoverlordofdata@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.hughes.android.dictionary.engine;

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;

import com.hughes.util.StringUtil;
import com.hughes.util.raf.RAFListSerializerSkippable;
import com.ibm.icu.text.Transliterator;

public class PairEntry extends AbstractEntry implements Comparable<PairEntry> {

    public final List<Pair> pairs;

    public PairEntry(final EntrySource entrySource) {
        super(entrySource);
        pairs = new ArrayList<>(1);
    }

    public PairEntry(final EntrySource entrySource, final String lang1, final String lang2) {
        this(entrySource);
        this.pairs.add(new Pair(lang1, lang2));
    }

    public PairEntry(final Dictionary dictionary, final DataInput raf, final int index)
    throws IOException {
        super(dictionary, raf, index);
        final int size = dictionary.dictFileVersion >= 7 ? StringUtil.readVarInt(raf) : raf.readInt();
        // Use singletonList for better performance in common case
        if (size == 1) pairs = Collections.singletonList(new Pair(raf.readUTF(), raf.readUTF()));
        else
        {
            pairs = new ArrayList<>(size);
            for (int i = 0; i < size; ++i) {
                pairs.add(new Pair(raf.readUTF(), raf.readUTF()));
            }
        }
    }

    private void fastWriteUTF(DataOutput raf, String s) throws IOException {
        int pos = 2;
        char[] in = s.toCharArray();
        byte[] out = new byte[in.length * 3 + 2];
        for (char c: in) {
            if (c < 128) out[pos++] = (byte)c;
            else if (c < 2048) {
                out[pos++] = (byte) (0xc0 | (c >> 6));
                out[pos++] = (byte) (0x80 | (c & 0x3f));
            } else {
                out[pos++] = (byte) (0xe0 | (c >> 12));
                out[pos++] = (byte) (0x80 | ((c >> 6) & 0x3f));
                out[pos++] = (byte) (0x80 | (c & 0x3f));
            }
        }
        int utflen = pos - 2;
        assert utflen < 0x10000;
        out[0] = (byte)(utflen >> 8);
        out[1] = (byte)utflen;
        raf.write(out, 0, pos);
    }

    @Override
    public void write(DataOutput raf) throws IOException {
        super.write(raf);
        StringUtil.writeVarInt(raf, pairs.size());
        for (Pair p : pairs) {
            assert p.lang1.length() > 0;
            fastWriteUTF(raf, p.lang1);
            fastWriteUTF(raf, p.lang2);
        }
    }

    static final class Serializer implements RAFListSerializerSkippable<PairEntry> {

        final Dictionary dictionary;

        Serializer(Dictionary dictionary) {
            this.dictionary = dictionary;
        }

        @Override
        public PairEntry read(DataInput raf, int index) throws IOException {
            return new PairEntry(dictionary, raf, index);
        }

        @Override
        public void skip(DataInput raf, int index) throws IOException {
            final int size;
            if (dictionary.dictFileVersion >= 7)
            {
                StringUtil.readVarInt(raf);
                size = StringUtil.readVarInt(raf);
            }
            else
            {
                raf.skipBytes(2);
                size = raf.readInt();
            }
            for (int i = 0; i < 2*size; ++i) {
                int l = raf.readUnsignedShort();
                raf.skipBytes(l);
            }
        }

        @Override
        public void write(DataOutput raf, PairEntry t) throws IOException {
            t.write(raf);
        }
    }

    @Override
    public void addToDictionary(final Dictionary dictionary) {
        assert index == -1;
        dictionary.pairEntries.add(this);
        index = dictionary.pairEntries.size() - 1;
    }

    @Override
    public RowBase CreateRow(int rowIndex, Index dictionaryIndex) {
        return new Row(this.index, rowIndex, dictionaryIndex);
    }

    // --------------------------------------------------------------------

    public static class Row extends RowBase {

        Row(final DataInput raf, final int thisRowIndex,
            final Index index, int extra) throws IOException {
            super(raf, thisRowIndex, index, extra);
        }

        Row(final int referenceIndex, final int thisRowIndex,
            final Index index) {
            super(referenceIndex, thisRowIndex, index);
        }

        @Override
        public String toString() {
            return getRawText(false);
        }

        public PairEntry getEntry() {
            return index.dict.pairEntries.get(referenceIndex);
        }

        @Override
        public void print(PrintStream out) {
            final PairEntry pairEntry = getEntry();
            for (int i = 0; i < pairEntry.pairs.size(); ++i) {
                out.print((i == 0 ? "  " : "    ") + pairEntry.pairs.get(i));
                out.println();
            }
        }

        @Override
        public String getRawText(boolean compact) {
            final PairEntry pairEntry = getEntry();
            return pairEntry.getRawText(compact);
        }

        @Override
        public RowMatchType matches(final List<String> searchTokens,
                                    final Pattern orderedMatchPattern, final Transliterator normalizer,
                                    final boolean swapPairEntries) {
            final int side = swapPairEntries ? 1 : 0;
            final List<Pair> pairs = getEntry().pairs;
            final String[] pairSides = new String[pairs.size()];
            for (int i = 0; i < pairs.size(); ++i) {
                pairSides[i] = normalizer.transform(pairs.get(i).get(side));
            }
            for (int i = searchTokens.size() - 1; i >= 0; --i) {
                final String searchToken = searchTokens.get(i);
                boolean found = false;
                for (final String pairSide : pairSides) {
                    found |= pairSide.contains(searchToken);
                }
                if (!found) {
                    return RowMatchType.NO_MATCH;
                }
            }
            for (final String pairSide : pairSides) {
                if (orderedMatchPattern.matcher(pairSide).find()) {
                    return RowMatchType.ORDERED_MATCH;
                }
            }
            return RowMatchType.BAG_OF_WORDS_MATCH;
        }

        @Override
        public int getSideLength(boolean swapPairEntries) {
            int result = 0;
            final int side = swapPairEntries ? 1 : 0;
            for (final Pair pair : getEntry().pairs) {
                result += pair.get(side).length();
            }
            return result;
        }

    }

    private String getRawText(final boolean compact) {
        if (compact) {
            return this.pairs.get(0).toStringTab();
        }
        final StringBuilder builder = new StringBuilder();
        for (int i = 0; i < this.pairs.size(); ++i) {
            if (i > 0) {
                builder.append(" | ");
            }
            builder.append(this.pairs.get(i).lang1);
        }
        builder.append("\t");
        for (int i = 0; i < this.pairs.size(); ++i) {
            if (i > 0) {
                builder.append(" | ");
            }
            builder.append(this.pairs.get(i).lang2);
        }
        return builder.toString();
    }

    @Override
    public int compareTo(/*@NonNull*/ final PairEntry that) {
        return this.getRawText(false).compareTo(that.getRawText(false));
    }

    @Override
    public String toString() {
        return getRawText(false);
    }

    // -----------------------------------------------------------------------

    public static final class Pair {

        public final String lang1;
        public final String lang2;

        @SuppressWarnings("WeakerAccess")
        public Pair(final String lang1, final String lang2) {
            this.lang1 = lang1;
            this.lang2 = lang2;
            assert lang1.trim().length() > 0 && lang2.trim().length() > 0 : "Empty pair!!!";
        }

        public Pair(final String lang1, final String lang2, final boolean swap) {
            this(swap ? lang2 : lang1, swap ? lang1 : lang2);
        }

        public String toString() {
            return lang1 + " :: " + lang2;
        }

        String toStringTab() {
            return lang1 + "\t" + lang2;
        }

        public String get(int i) {
            if (i == 0) {
                return lang1;
            } else if (i == 1) {
                return lang2;
            }
            throw new IllegalArgumentException();
        }

        @Override
        public boolean equals(Object o)
        {
            if (o == this) return true;
            if (!(o instanceof Pair)) return false;
            Pair p = (Pair)o;
            return p.lang1.equals(lang1) && p.lang2.equals(lang2);
        }

        @Override
        public int hashCode()
        {
            return (lang1 + "|" + lang2).hashCode();
        }
    }
}


text:
package org.gobiiproject.gobiiapimodel.types;

import org.gobiiproject.gobiimodel.utils.LineUtils;

/**
 * Created by Phil on 5/13/2016.
 */

public enum GobiiServiceRequestId {

    URL_AUTH("auth"),
    URL_PING("ping"),
    URL_PROJECTS("projects"),
    URL_NAME_ID_LIST_DEPRECATED("nameidlist"),
    URL_NAMES("names"),
    URL_FILE_LOAD("files/loader"),
    URL_FILE_LOAD_INSTRUCTIONS("instructions/loader"),
    URL_FILE_EXTRACTOR_INSTRUCTIONS("instructions/extractor"),
    URL_FILE_EXTRACTOR_STATUS("instructions/extractor/status"),
    URL_DISPLAY("displays"),
    URL_CV("cvs"),
    URL_CVGROUP("cvgroups"),
    URL_CONTACTS("contacts"),
    URL_CONTACT_SEARCH("contact-search"),
    URL_ORGANIZATION_SEARCH("organization-search"),
    URL_REFERENCE("references"),
    URL_EXPERIMENTS("experiments"),
    URL_DATASETS("datasets"),
    URL_DATASETTYPES("datasets/types"),
    URL_ANALYSIS("analyses"),
    URL_MARKERGROUP("markergroups"),
    URL_MANIFEST("manifests"),
    URL_ORGANIZATION("organizations"),
    URL_PLATFORM("platforms"),
    URL_MAPSET("mapsets"),
    URL_CONFIGSETTINGS("configsettings"),
    URL_ROLES("roles"),
    URL_MARKERS("markers"),
    URL_MARKER_SEARCH("marker-search"),
    URL_CALLS("calls"),
    URL_STUDIES_SEARCH("studies-search"),
    URL_STUDIES("studies"),
    URL_GERMPLASM("germplasm"),
    URL_OBSERVATION_VARIABLES("observationVariables"),
    URL_PROTOCOL("protocols"),
    URL_VENDORS("vendors"),
    URL_ALLELE_MATRIX_SEARCH("allelematrix-search"),
    URL_ALLELE_MATRIX_SEARCH_STATUS("allelematrix-search/status"),
    URL_ALLELE_MATRICES("allelematrices"),
    URL_FILES("files");

    private String requestPath;

    GobiiServiceRequestId(String requestPath) {
        this.requestPath = requestPath;
    }

    public String getResourcePath() {
        return this.requestPath;
    }

    public String getRequestUrl(String contextRoot, String secondaryPath) throws Exception {

        String returnVal = "";

        if (!LineUtils.isNullOrEmpty(contextRoot)) {
            returnVal = contextRoot;
        }

        if (!LineUtils.isNullOrEmpty(secondaryPath)) {
            returnVal += secondaryPath;
        }

        returnVal += this.getResourcePath();

        return returnVal;
    }

}