Ejemplo n.º 1
0
def handlePermissionRequest(providerSession, service, request):
    """ Respond to a PermissionRequest.

    Only accept requests with applicationId `ALLOWED_APP_ID`.
    """
    assert request.messageType() == PERMISSION_REQUEST

    disallowed = 1
    if request.hasElement("applicationId") and \
            request.getElementAsInteger("applicationId") == ALLOWED_APP_ID:
        disallowed = 0

    response = service.createResponseEvent(request.correlationIds()[0])
    formatter = blpapi.EventFormatter(response)
    formatter.appendResponse(PERMISSION_RESPONSE)

    topics = request.getElement(TOPICS)
    formatter.pushElement(TOPIC_PERMISSION)

    for i in range(topics.numValues()):
        formatter.appendElement()
        formatter.setElement(TOPIC, topics.getValueAsString(i))
        formatter.setElement(RESULT, disallowed)
        if disallowed:
            formatter.pushElement(REASON)
            formatter.setElement(SOURCE, RESOLVER_ID)
            formatter.setElement(CATEGORY, "NOT_AUTHORIZED")
            formatter.setElement(SUBCATEGORY, "")
            formatter.setElement(DESCRIPTION, "Only app 1234 allowed")
            formatter.popElement()
        formatter.popElement()

    formatter.popElement()

    providerSession.sendResponse(response)
    return True
Ejemplo n.º 2
0
    def processEvent(self, event, session):
        global g_availableTopicCount, g_running

        if event.eventType() == blpapi.Event.SESSION_STATUS:
            for msg in event:
                print msg
                if msg.messageType() == SESSION_TERMINATED:
                    g_running = False

        elif event.eventType() == blpapi.Event.TOPIC_STATUS:
            topicList = blpapi.TopicList()

            for msg in event:
                print msg
                if msg.messageType() == TOPIC_SUBSCRIBED:
                    topicStr = msg.getElementAsString("topic")
                    with g_mutex:
                        if topicStr not in g_streams:
                            # TopicList knows how to add an entry based on a
                            # TOPIC_SUBSCRIBED message.
                            topicList.add(msg)
                            g_streams[topicStr] = MyStream(
                                topicStr, self.fields)
                        stream = g_streams[topicStr]
                        stream.isSubscribed = True
                        if stream.isAvailable():
                            g_availableTopicCount += 1
                            g_condition.notifyAll()

                elif msg.messageType() == TOPIC_UNSUBSCRIBED:
                    topicStr = msg.getElementAsString("topic")
                    with g_mutex:
                        if topicStr not in g_streams:
                            # We should never be coming here.
                            # TOPIC_UNSUBSCRIBED can not come before
                            # a TOPIC_SUBSCRIBED or TOPIC_CREATED
                            continue
                        stream = g_streams[topicStr]
                        if stream.isAvailable():
                            g_availableTopicCount -= 1
                            g_condition.notifyAll()
                        stream.isSubscribed = False

                elif msg.messageType() == TOPIC_CREATED:
                    topicStr = msg.getElementAsString("topic")
                    with g_mutex:
                        if topicStr not in g_streams:
                            g_streams[topicStr] = MyStream(
                                topicStr, self.fields)
                        stream = g_streams[topicStr]
                        try:
                            stream.topic = session.getTopic(msg)
                        except blpapi.Exception as e:
                            print "Exception while processing " \
                                "TOPIC_CREATED: %s" % e
                            continue

                        if stream.isAvailable():
                            g_availableTopicCount = g_availableTopicCount + 1
                            g_condition.notifyAll()

                elif msg.messageType() == TOPIC_RECAP:
                    # Here we send a recap in response to a Recap request.
                    try:
                        topicStr = msg.getElementAsString("topic")
                        recapEvent = None

                        with g_mutex:
                            if topicStr not in g_streams:
                                continue
                            stream = g_streams[topicStr]
                            if not stream.isAvailable():
                                continue

                            topic = session.getTopic(msg)
                            service = topic.service()
                            recapCid = msg.correlationIds()[0]

                            recapEvent = service.createPublishEvent()
                            elementDef = \
                                service.getEventDefinition(self.messageType)

                            eventFormatter = blpapi.EventFormatter(recapEvent)
                            eventFormatter.appendRecapMessage(topic, recapCid)

                            stream.fillData(eventFormatter, elementDef)

                        session.publish(recapEvent)

                    except blpapi.Exception as e:
                        print "Exception while processing TOPIC_RECAP: %s" % e
                        continue

            if topicList.size() > 0:
                # createTopicsAsync will result in RESOLUTION_STATUS,
                # TOPIC_CREATED events.
                session.createTopicsAsync(topicList)

        elif event.eventType() == blpapi.Event.RESOLUTION_STATUS:
            for msg in event:
                print msg

        elif event.eventType() == blpapi.Event.REQUEST:
            service = session.getService(self.serviceName)
            for msg in event:
                print msg

                if msg.messageType() == PERMISSION_REQUEST:
                    # Similar to createPublishEvent. We assume just one
                    # service - self.serviceName. A responseEvent can only be
                    # for single request so we can specify the correlationId -
                    # which establishes context - when we create the Event.

                    response = \
                        service.createResponseEvent(msg.correlationIds()[0])
                    permission = 1  # ALLOWED: 0, DENIED: 1
                    ef = blpapi.EventFormatter(response)
                    if msg.hasElement("uuid"):
                        uuid = msg.getElementAsInteger("uuid")
                        permission = 0
                    if msg.hasElement("applicationId"):
                        applicationId = \
                            msg.getElementAsInteger("applicationId")
                        permission = 0

                    # In appendResponse the string is the name of the
                    # operation, the correlationId indicates which request we
                    # are responding to.
                    ef.appendResponse("PermissionResponse")
                    ef.pushElement("topicPermissions")

                    # For each of the topics in the request, add an entry to
                    # the response.
                    topicsElement = msg.getElement(TOPICS).values()
                    for topic in topicsElement:
                        ef.appendElement()
                        ef.setElement("topic", topic)
                        ef.setElement("result", permission)
                        if permission == 1:  # DENIED
                            ef.pushElement("reason")
                            ef.setElement("source", "My Publisher Name")
                            ef.setElement("category", "NOT_AUTHORIZED")
                            ef.setElement("subcategory",
                                          "Publisher Controlled")
                            ef.setElement(
                                "description",
                                "Permission denied by My Publisher Name")
                            ef.popElement()
                        elif self.eids:
                            ef.pushElement("permissions")
                            ef.appendElement()
                            ef.setElement("permissionService", "//blp/blpperm")
                            ef.pushElement("eids")
                            for e in self.eids:
                                ef.appendValue(e)
                            ef.popElement()
                            ef.popElement()
                            ef.popElement()
                        ef.popElement()
                    ef.popElement()

                    # Service is implicit in the Event. sendResponse has a
                    # second parameter - partialResponse - that defaults to
                    # false.
                    session.sendResponse(response)

        else:
            for msg in event:
                print msg
                cids = msg.correlationIds()
                with g_mutex:
                    for cid in cids:
                        if cid in g_authorizationStatus:
                            if msg.messageType() == AUTHORIZATION_SUCCESS:
                                g_authorizationStatus[cid] = \
                                    AuthorizationStatus.AUTHORIZED
                            else:
                                g_authorizationStatus[cid] = \
                                    AuthorizationStatus.FAILED

        return True
Ejemplo n.º 3
0
def main():
    options = parseCmdLine()

    # Fill SessionOptions
    sessionOptions = blpapi.SessionOptions()
    for idx, host in enumerate(options.hosts):
        sessionOptions.setServerAddress(host, options.port, idx)
    sessionOptions.setAuthenticationOptions(options.auth)
    sessionOptions.setAutoRestartOnDisconnection(True)

    # NOTE: If running without a backup server, make many attempts to
    # connect/reconnect to give that host a chance to come back up (the
    # larger the number, the longer it will take for SessionStartupFailure
    # to come on startup, or SessionTerminated due to inability to fail
    # over).  We don't have to do that in a redundant configuration - it's
    # expected at least one server is up and reachable at any given time,
    # so only try to connect to each server once.
    sessionOptions.setNumStartAttempts(1 if len(options.hosts) > 1 else 1000)

    print "Connecting to port %d on %s" % (options.port, " ".join(
        options.hosts))

    PUBLISH_MESSAGE_TYPE = blpapi.Name(options.messageType)

    myEventHandler = MyEventHandler(options.service, PUBLISH_MESSAGE_TYPE,
                                    options.fields, options.eids)

    # Create a Session
    session = blpapi.ProviderSession(sessionOptions,
                                     myEventHandler.processEvent)

    # Start a Session
    if not session.start():
        print "Failed to start session."
        return

    providerIdentity = session.createIdentity()

    if options.auth:
        isAuthorized = False
        authServiceName = "//blp/apiauth"
        if session.openService(authServiceName):
            authService = session.getService(authServiceName)
            isAuthorized = authorize(authService, providerIdentity, session,
                                     blpapi.CorrelationId("auth"))
        if not isAuthorized:
            print "No authorization"
            return

    serviceOptions = blpapi.ServiceRegistrationOptions()
    if options.groupId is not None:
        serviceOptions.setGroupId(options.groupId)
    serviceOptions.setServicePriority(options.priority)

    if not session.registerService(options.service, providerIdentity,
                                   serviceOptions):
        print "Failed to register '%s'" % options.service
        return

    service = session.getService(options.service)
    elementDef = service.getEventDefinition(PUBLISH_MESSAGE_TYPE)

    try:
        while g_running:
            event = service.createPublishEvent()

            with g_condition:
                while g_availableTopicCount == 0:
                    # Set timeout to 1 - give a chance for CTRL-C
                    g_condition.wait(1)
                    if not g_running:
                        return

                eventFormatter = blpapi.EventFormatter(event)
                for topicName, stream in g_streams.iteritems():
                    if not stream.isAvailable():
                        continue
                    stream.next()
                    eventFormatter.appendMessage(PUBLISH_MESSAGE_TYPE,
                                                 stream.topic)
                    stream.fillData(eventFormatter, elementDef)

            for msg in event:
                print msg

            session.publish(event)
            time.sleep(10)

    finally:
        # Stop the session
        session.stop()
Ejemplo n.º 4
0
def main():
    """Main function"""

    options = parseCmdLine()

    # Fill SessionOptions
    sessionOptions = prepareZfpSessionOptions(options) \
        if options.remote \
        else prepareStandardSessionOptions(options)
    sessionOptions.setAuthenticationOptions(options.auth)
    sessionOptions.setAutoRestartOnDisconnection(True)

    myEventHandler = MyEventHandler()

    # Create a Session
    session = blpapi.ProviderSession(sessionOptions,
                                     myEventHandler.processEvent)

    # Start a Session
    if not session.start():
        print("Failed to start session.")
        return

    providerIdentity = session.createIdentity()

    if options.auth:
        isAuthorized = False
        authServiceName = "//blp/apiauth"
        if session.openService(authServiceName):
            authService = session.getService(authServiceName)
            isAuthorized = authorize(
                authService, providerIdentity, session,
                blpapi.CorrelationId("auth"))
        if not isAuthorized:
            print("No authorization")
            return

    topicList = blpapi.TopicList()
    topicList.add(options.service + options.topic,
                  blpapi.CorrelationId(MyStream(options.topic)))

    # Create topics
    session.createTopics(topicList,
                         blpapi.ProviderSession.AUTO_REGISTER_SERVICES,
                         providerIdentity)
    # createTopics() is synchronous, topicList will be updated
    # with the results of topic creation (resolution will happen
    # under the covers)

    streams = []
    for i in range(topicList.size()):
        stream = topicList.correlationIdAt(i).value()
        status = topicList.statusAt(i)

        if status == blpapi.TopicList.CREATED:
            stream.topic = session.getTopic(topicList.messageAt(i))
            streams.append(stream)
        else:
            print("Stream '%s': topic not resolved, status = %d" % (
                stream.id, status))

    service = session.getService(options.service)

    try:
        # Now we will start publishing
        value = 1
        while streams and g_running:
            event = service.createPublishEvent()
            eventFormatter = blpapi.EventFormatter(event)

            for stream in streams:
                value += 1
                eventFormatter.appendMessage(MARKET_DATA, stream.topic)
                eventFormatter.setElement("BID", 0.5 * value)
                eventFormatter.setElement("ASK", value)

            for msg in event:
                print(msg)

            session.publish(event)
            time.sleep(10)
    finally:
        # Stop the session
        session.stop()
def main():
    options = parseCmdLine()

    # Fill SessionOptions
    sessionOptions = blpapi.SessionOptions()
    for idx, host in enumerate(options.hosts):
        sessionOptions.setServerAddress(host, options.port, idx)
    sessionOptions.setAuthenticationOptions(options.auth)
    sessionOptions.setAutoRestartOnDisconnection(True)
    sessionOptions.setNumStartAttempts(len(options.hosts))

    myEventHandler = MyEventHandler()

    # Create a Session
    session = blpapi.ProviderSession(sessionOptions,
                                     myEventHandler.processEvent)

    # Start a Session
    if not session.start():
        print "Failed to start session."
        return

    providerIdentity = session.createIdentity()

    if options.auth:
        isAuthorized = False
        authServiceName = "//blp/apiauth"
        if session.openService(authServiceName):
            authService = session.getService(authServiceName)
            isAuthorized = authorize(authService, providerIdentity, session,
                                     blpapi.CorrelationId("auth"))
        if not isAuthorized:
            print "No authorization"
            return

    topicList = blpapi.TopicList()
    topicList.add(options.service + "/" + options.topic,
                  blpapi.CorrelationId(MyStream(options.topic)))

    # Create topics
    session.createTopics(topicList,
                         blpapi.ProviderSession.AUTO_REGISTER_SERVICES,
                         providerIdentity)
    # createTopics() is synchronous, topicList will be updated
    # with the results of topic creation (resolution will happen
    # under the covers)

    streams = []
    for i in xrange(topicList.size()):
        stream = topicList.correlationIdAt(i).value()
        status = topicList.statusAt(i)
        topicString = topicList.topicStringAt(i)

        if (status == blpapi.TopicList.CREATED):
            stream.topic = session.getTopic(topicList.messageAt(i))
            streams.append(stream)
        else:
            print "Stream '%s': topic not resolved, status = %d" % (stream.id,
                                                                    status)

    service = session.getService(options.service)

    try:
        # Now we will start publishing
        while streams and g_running:
            event = service.createPublishEvent()
            eventFormatter = blpapi.EventFormatter(event)

            for stream in streams:
                eventFormatter.appendMessage("PageData", stream.topic)
                eventFormatter.pushElement("rowUpdate")

                eventFormatter.appendElement()
                eventFormatter.setElement("rowNum", 1)
                eventFormatter.pushElement("spanUpdate")

                eventFormatter.appendElement()
                eventFormatter.setElement("startCol", 20)
                eventFormatter.setElement("length", 4)
                eventFormatter.setElement("text", "TEST")
                eventFormatter.popElement()

                eventFormatter.appendElement()
                eventFormatter.setElement("startCol", 25)
                eventFormatter.setElement("length", 4)
                eventFormatter.setElement("text", "PAGE")
                eventFormatter.popElement()

                tm = time.strftime("%X")
                eventFormatter.appendElement()
                eventFormatter.setElement("startCol", 30)
                eventFormatter.setElement("length", len(tm))
                eventFormatter.setElement("text", tm)
                eventFormatter.setElement("attr", "BLINK")
                eventFormatter.popElement()

                eventFormatter.popElement()
                eventFormatter.popElement()

                eventFormatter.appendElement()
                eventFormatter.setElement("rowNum", 2)
                eventFormatter.pushElement("spanUpdate")
                eventFormatter.appendElement()
                eventFormatter.setElement("startCol", 20)
                eventFormatter.setElement("length", 9)
                eventFormatter.setElement("text", "---------")
                eventFormatter.setElement("attr", "UNDERLINE")
                eventFormatter.popElement()
                eventFormatter.popElement()
                eventFormatter.popElement()

                eventFormatter.appendElement()
                eventFormatter.setElement("rowNum", 3)
                eventFormatter.pushElement("spanUpdate")
                eventFormatter.appendElement()
                eventFormatter.setElement("startCol", 10)
                eventFormatter.setElement("length", 9)
                eventFormatter.setElement("text", "TEST LINE")
                eventFormatter.popElement()
                eventFormatter.appendElement()
                eventFormatter.setElement("startCol", 23)
                eventFormatter.setElement("length", 5)
                eventFormatter.setElement("text", "THREE")
                eventFormatter.popElement()
                eventFormatter.popElement()
                eventFormatter.popElement()
                eventFormatter.popElement()

                eventFormatter.setElement("contributorId",
                                          options.contributorId)
                eventFormatter.setElement("productCode", 1)
                eventFormatter.setElement("pageNumber", 1)

            for msg in event:
                print msg

            session.publish(event)
            time.sleep(10)
    finally:
        # Stop the session
        session.stop()
Ejemplo n.º 6
0
def main():
    options = parseCmdLine()

    # Fill SessionOptions
    sessionOptions = blpapi.SessionOptions()
    for idx, host in enumerate(options.hosts):
        sessionOptions.setServerAddress(host, options.port, idx)
    sessionOptions.setAuthenticationOptions(options.auth)
    sessionOptions.setAutoRestartOnDisconnection(True)

    # NOTE: If running without a backup server, make many attempts to
    # connect/reconnect to give that host a chance to come back up (the
    # larger the number, the longer it will take for SessionStartupFailure
    # to come on startup, or SessionTerminated due to inability to fail
    # over).  We don't have to do that in a redundant configuration - it's
    # expected at least one server is up and reachable at any given time,
    # so only try to connect to each server once.
    sessionOptions.setNumStartAttempts(1 if len(options.hosts) > 1 else 1000)

    print("Connecting to port %d on %s" %
          (options.port, " ".join(options.hosts)))

    PUBLISH_MESSAGE_TYPE = blpapi.Name(options.messageType)

    myEventHandler = MyEventHandler(options.service, PUBLISH_MESSAGE_TYPE,
                                    options.fields, options.eids, options.rssc)

    # Create a Session
    session = blpapi.ProviderSession(sessionOptions,
                                     myEventHandler.processEvent)

    # Start a Session
    if not session.start():
        print("Failed to start session.")
        return

    providerIdentity = session.createIdentity()

    if options.auth:
        isAuthorized = False
        authServiceName = "//blp/apiauth"
        if session.openService(authServiceName):
            authService = session.getService(authServiceName)
            isAuthorized = authorize(authService, providerIdentity, session,
                                     blpapi.CorrelationId("auth"))
        if not isAuthorized:
            print("No authorization")
            return

    serviceOptions = blpapi.ServiceRegistrationOptions()
    if options.groupId is not None:
        serviceOptions.setGroupId(options.groupId)
    serviceOptions.setServicePriority(options.priority)

    if options.ssc:
        sscBegin, sscEnd, sscPriority = map(int, options.ssc.split(","))
        print(("Adding active sub service code range [%s, %s] @ %s" %
               (sscBegin, sscEnd, sscPriority)))
        try:
            serviceOptions.addActiveSubServiceCodeRange(
                sscBegin, sscEnd, sscPriority)
        except blpapi.Exception as e:
            print(("FAILED to add active sub service codes."
                   " Exception %s" % e.description()))

    if not session.registerService(options.service, providerIdentity,
                                   serviceOptions):
        print("Failed to register '%s'" % options.service)
        return

    service = session.getService(options.service)
    elementDef = service.getEventDefinition(PUBLISH_MESSAGE_TYPE)
    eventCount = 0

    try:
        numPublished = 0
        while g_running:
            event = service.createPublishEvent()

            with g_condition:
                while g_availableTopicCount == 0:
                    # Set timeout to 1 - give a chance for CTRL-C
                    g_condition.wait(1)
                    if not g_running:
                        return

                publishNull = False
                if (options.clearInterval > 0
                        and eventCount == options.clearInterval):
                    eventCount = 0
                    publishNull = True
                eventFormatter = blpapi.EventFormatter(event)
                for topicName, stream in g_streams.items():
                    if not stream.isAvailable():
                        continue
                    eventFormatter.appendMessage(PUBLISH_MESSAGE_TYPE,
                                                 stream.topic)
                    if publishNull:
                        stream.fillDataNull(eventFormatter, elementDef)
                    else:
                        eventCount += 1
                        stream.next()
                        stream.fillData(eventFormatter, elementDef)

            for msg in event:
                print(msg)

            session.publish(event)
            time.sleep(1)
            numPublished += 1
            if numPublished % 10 == 0:
                deactivate(options, session)
                time.sleep(30)
                activate(options, session)

    finally:
        # Stop the session
        session.stop()
Ejemplo n.º 7
0
    def processEvent(self, event, session):
        global g_running

        print("Server received an event")
        if event.eventType() == blpapi.Event.SESSION_STATUS:
            for msg in event:
                print(msg)
                if msg.messageType() == SESSION_TERMINATED:
                    g_running = False

        elif event.eventType() == blpapi.Event.RESOLUTION_STATUS:
            for msg in event:
                print(msg)

        elif event.eventType() == blpapi.Event.REQUEST:
            service = session.getService(self.serviceName)
            for msg in event:
                print(msg)

                if msg.messageType() == blpapi.Name("ReferenceDataRequest"):
                    # Similar to createPublishEvent. We assume just one
                    # service - self.serviceName. A responseEvent can only be
                    # for single request so we can specify the correlationId -
                    # which establishes context - when we create the Event.

                    if msg.hasElement("timestamp"):
                        requestTime = msg.getElementAsFloat("timestamp")
                        latency = time.time() - requestTime
                        print("Response latency =", latency)

                    response = \
                        service.createResponseEvent(msg.correlationIds()[0])
                    ef = blpapi.EventFormatter(response)

                    # In appendResponse the string is the name of the
                    # operation, the correlationId indicates which request we
                    # are responding to.
                    ef.appendResponse("ReferenceDataRequest")
                    securities = msg.getElement("securities")
                    fields = msg.getElement("fields")
                    ef.setElement("timestamp", time.time())
                    ef.pushElement("securityData")
                    for security in securities.values():
                        ef.appendElement()
                        ef.setElement("security", security)
                        ef.pushElement("fieldData")

                        for field in fields.values():
                            ef.appendElement()
                            ef.setElement("fieldId", field)
                            ef.pushElement("data")
                            ef.setElement("doubleValue", time.time())
                            ef.popElement()
                            ef.popElement()

                        ef.popElement()
                        ef.popElement()

                    # Service is implicit in the Event. sendResponse has a
                    # second parameter - partialResponse - that defaults to
                    # false.
                    session.sendResponse(response)

        else:
            for msg in event:
                print(msg)
        return True
    def processEvent(self, event, session):
        global g_availableTopicCount, g_running

        if event.eventType() == blpapi.Event.SESSION_STATUS:
            for msg in event:
                print(msg)
                if msg.messageType() == SESSION_TERMINATED:
                    g_running = False

        elif event.eventType() == blpapi.Event.TOPIC_STATUS:
            topicList = blpapi.TopicList()

            for msg in event:
                print(msg)
                if msg.messageType() == TOPIC_SUBSCRIBED:
                    topicStr = msg.getElementAsString("topic")
                    with g_mutex:
                        if topicStr not in g_streams:
                            # TopicList knows how to add an entry based on a
                            # TOPIC_SUBSCRIBED message.
                            topicList.add(msg)
                            g_streams[topicStr] = MyStream(topicStr)
                        stream = g_streams[topicStr]
                        stream.isSubscribed = True
                        if stream.isAvailable():
                            g_availableTopicCount += 1
                            g_condition.notifyAll()

                elif msg.messageType() == TOPIC_UNSUBSCRIBED:
                    topicStr = msg.getElementAsString("topic")
                    with g_mutex:
                        if topicStr not in g_streams:
                            # We should never be coming here.
                            # TOPIC_UNSUBSCRIBED can not come before
                            # a TOPIC_SUBSCRIBED or TOPIC_CREATED
                            continue
                        stream = g_streams[topicStr]
                        if stream.isAvailable():
                            g_availableTopicCount -= 1
                            g_condition.notifyAll()
                        stream.isSubscribed = False

                elif msg.messageType() == TOPIC_CREATED:
                    topicStr = msg.getElementAsString("topic")
                    with g_mutex:
                        if topicStr not in g_streams:
                            g_streams[topicStr] = MyStream(topicStr)
                        stream = g_streams[topicStr]
                        try:
                            stream.topic = session.getTopic(msg)
                        except blpapi.Exception as e:
                            print("Exception while processing " \
                                "TOPIC_CREATED: %s" % e)
                            continue

                        if stream.isAvailable():
                            g_availableTopicCount += 1
                            g_condition.notifyAll()

                elif msg.messageType() == TOPIC_RECAP:
                    # Here we send a recap in response to a Recap request.
                    try:
                        topicStr = msg.getElementAsString("topic")
                        recapEvent = None

                        with g_mutex:
                            if topicStr not in g_streams:
                                continue
                            stream = g_streams[topicStr]
                            if not stream.isAvailable():
                                continue

                            topic = session.getTopic(msg)
                            service = topic.service()
                            recapCid = msg.correlationIds()[0]

                            recapEvent = service.createPublishEvent()
                            evFormatter = blpapi.EventFormatter(recapEvent)
                            evFormatter.appendRecapMessage(topic, recapCid)
                            evFormatter.setElement("numRows", 25)
                            evFormatter.setElement("numCols", 80)
                            evFormatter.pushElement("rowUpdate")

                            for i in range(1, 6):
                                evFormatter.appendElement()
                                evFormatter.setElement("rowNum", i)
                                evFormatter.pushElement("spanUpdate")
                                evFormatter.appendElement()
                                evFormatter.setElement("startCol", 1)
                                evFormatter.setElement("length", 10)
                                evFormatter.setElement("text", "RECAP")
                                evFormatter.popElement()
                                evFormatter.popElement()
                                evFormatter.popElement()

                            evFormatter.popElement()

                        session.publish(recapEvent)

                    except blpapi.Exception as e:
                        print("Exception while processing TOPIC_RECAP: %s" % e)
                        continue

            if topicList.size() > 0:
                # createTopicsAsync will result in RESOLUTION_STATUS,
                # TOPIC_CREATED events.
                session.createTopicsAsync(topicList)

        elif event.eventType() == blpapi.Event.RESOLUTION_STATUS:
            for msg in event:
                print(msg)

        elif event.eventType() == blpapi.Event.REQUEST:
            service = session.getService(self.serviceName)
            for msg in event:
                print(msg)

                if msg.messageType() == PERMISSION_REQUEST:
                    # This example always sends a 'PERMISSIONED' response.
                    # See 'MktdataPublisherExample' on how to parse a
                    # Permission request and send an appropriate
                    # 'PermissionResponse'.

                    response = \
                        service.createResponseEvent(msg.correlationIds()[0])
                    permission = 0  # ALLOWED: 0, DENIED: 1
                    ef = blpapi.EventFormatter(response)
                    ef.appendResponse("PermissionResponse")
                    ef.pushElement("topicPermissions")

                    # For each of the topics in the request, add an entry to
                    # the response.
                    topicsElement = list(msg.getElement(TOPICS).values())
                    for topic in topicsElement:
                        ef.appendElement()
                        ef.setElement("topic", topic)
                        ef.setElement("result", permission)
                        ef.popElement()
                    ef.popElement()

                    session.sendResponse(response)

        else:
            for msg in event:
                print(msg)
                cids = msg.correlationIds()
                with g_mutex:
                    for cid in cids:
                        if cid in g_authorizationStatus:
                            if msg.messageType() == AUTHORIZATION_SUCCESS:
                                g_authorizationStatus[cid] = \
                                    AuthorizationStatus.AUTHORIZED
                            else:
                                g_authorizationStatus[cid] = \
                                    AuthorizationStatus.FAILED

        return True
def main():
    options = parseCmdLine()

    # Fill SessionOptions
    sessionOptions = blpapi.SessionOptions()
    for idx, host in enumerate(options.hosts):
        sessionOptions.setServerAddress(host, options.port, idx)
    sessionOptions.setAuthenticationOptions(options.auth)
    sessionOptions.setAutoRestartOnDisconnection(True)
    sessionOptions.setNumStartAttempts(len(options.hosts))

    print("Connecting to port %d on %s" %
          (options.port, " ".join(options.hosts)))

    myEventHandler = MyEventHandler(options.service)

    # Create a Session
    session = blpapi.ProviderSession(sessionOptions,
                                     myEventHandler.processEvent)

    # Start a Session
    if not session.start():
        print("Failed to start session.")
        return

    providerIdentity = session.createIdentity()

    if options.auth:
        isAuthorized = False
        authServiceName = "//blp/apiauth"
        if session.openService(authServiceName):
            authService = session.getService(authServiceName)
            isAuthorized = authorize(authService, providerIdentity, session,
                                     blpapi.CorrelationId("auth"))
        if not isAuthorized:
            print("No authorization")
            return

    serviceOptions = blpapi.ServiceRegistrationOptions()
    if options.groupId is not None:
        serviceOptions.setGroupId(options.groupId)
    serviceOptions.setServicePriority(options.priority)

    if not session.registerService(options.service, providerIdentity,
                                   serviceOptions):
        print("Failed to register '%s'" % options.service)
        return

    service = session.getService(options.service)

    try:
        # Now we will start publishing
        value = 1
        while g_running:
            event = service.createPublishEvent()

            with g_condition:
                while g_availableTopicCount == 0:
                    # Set timeout to 1 - give a chance for CTRL-C
                    g_condition.wait(1)
                    if not g_running:
                        return

                eventFormatter = blpapi.EventFormatter(event)
                for topicName, stream in g_streams.items():
                    if not stream.isAvailable():
                        continue

                    value += 1

                    if not stream.isInitialPaintSent:
                        eventFormatter.appendRecapMessage(stream.topic)
                        eventFormatter.setElement("numRows", 25)
                        eventFormatter.setElement("numCols", 80)
                        eventFormatter.pushElement("rowUpdate")
                        for i in range(1, 6):
                            eventFormatter.appendElement()
                            eventFormatter.setElement("rowNum", i)
                            eventFormatter.pushElement("spanUpdate")
                            eventFormatter.appendElement()
                            eventFormatter.setElement("startCol", 1)
                            eventFormatter.setElement("length", 10)
                            eventFormatter.setElement("text", "INITIAL")
                            eventFormatter.setElement("fgColor", "RED")
                            eventFormatter.popElement()
                            eventFormatter.popElement()
                            eventFormatter.popElement()
                        eventFormatter.popElement()
                        stream.isInitialPaintSent = True

                    eventFormatter.appendMessage("RowUpdate", stream.topic)
                    eventFormatter.setElement("rowNum", 1)
                    eventFormatter.pushElement("spanUpdate")
                    eventFormatter.appendElement()
                    START_COL = blpapi.Name("startCol")
                    eventFormatter.setElement(START_COL, 1)
                    strValue = str(value)
                    eventFormatter.setElement("length", len(strValue))
                    eventFormatter.setElement("text", strValue)
                    eventFormatter.popElement()
                    eventFormatter.popElement()

            for msg in event:
                print(msg)

            session.publish(event)
            time.sleep(10)

    finally:
        # Stop the session
        session.stop()
Ejemplo n.º 10
0
def main():
    options = parseCmdLine()

    # Fill SessionOptions
    sessionOptions = blpapi.SessionOptions()
    for idx, host in enumerate(options.hosts):
        sessionOptions.setServerAddress(host, options.port, idx)
    sessionOptions.setAuthenticationOptions(options.auth)
    sessionOptions.setAutoRestartOnDisconnection(True)

    # NOTE: If running without a backup server, make many attempts to
    # connect/reconnect to give that host a chance to come back up (the
    # larger the number, the longer it will take for SessionStartupFailure
    # to come on startup, or SessionTerminated due to inability to fail
    # over).  We don't have to do that in a redundant configuration - it's
    # expected at least one server is up and reachable at any given time,
    # so only try to connect to each server once.
    sessionOptions.setNumStartAttempts(1 if len(options.hosts) > 1 else 1000)

    myEventHandler = MyEventHandler()

    # Create a Session
    session = blpapi.ProviderSession(sessionOptions,
                                     myEventHandler.processEvent)

    # Start a Session
    if not session.start():
        print("Failed to start session.")
        return

    providerIdentity = session.createIdentity()

    if options.auth:
        isAuthorized = False
        authServiceName = "//blp/apiauth"
        if session.openService(authServiceName):
            authService = session.getService(authServiceName)
            isAuthorized = authorize(authService, providerIdentity, session,
                                     blpapi.CorrelationId("auth"))
        if not isAuthorized:
            print("No authorization")
            return

    if options.groupId is not None:
        # NOTE: will perform explicit service registration here, instead
        # of letting createTopics do it, as the latter approach doesn't
        # allow for custom ServiceRegistrationOptions.
        serviceOptions = blpapi.ServiceRegistrationOptions()
        serviceOptions.setGroupId(options.groupId)
        if not session.registerService(options.service, identity,
                                       serviceOptions):
            print("Failed to register %s" % options.service)
            return

    topicList = blpapi.TopicList()
    topicList.add(options.service + "/ticker/" + options.topic,
                  blpapi.CorrelationId(MyStream(options.topic)))

    # Create topics
    session.createTopics(topicList,
                         blpapi.ProviderSession.AUTO_REGISTER_SERVICES,
                         providerIdentity)
    # createTopics() is synchronous, topicList will be updated
    # with the results of topic creation (resolution will happen
    # under the covers)

    streams = []
    for i in range(topicList.size()):
        stream = topicList.correlationIdAt(i).value()
        status = topicList.statusAt(i)
        topicString = topicList.topicStringAt(i)

        if (status == blpapi.TopicList.CREATED):
            print("Start publishing on topic: %s" % topicString)
            stream.topic = session.getTopic(topicList.messageAt(i))
            streams.append(stream)
        else:
            print("Stream '%s': topic not created, status = %d" %
                  (stream.id, status))

    service = session.getService(options.service)
    PUBLISH_MESSAGE_TYPE = blpapi.Name(options.messageType)

    try:
        # Now we will start publishing
        tickCount = 1
        while streams and g_running:
            event = service.createPublishEvent()
            eventFormatter = blpapi.EventFormatter(event)

            for stream in streams:
                topic = stream.topic
                if not topic.isActive():
                    print("[WARN] Publishing on an inactive topic.")
                eventFormatter.appendMessage(PUBLISH_MESSAGE_TYPE, topic)

                for i, f in enumerate(options.fields):
                    eventFormatter.setElement(f, tickCount + i + 1.0)

                tickCount += 1

            for msg in event:
                print(msg)

            session.publish(event)
            time.sleep(10)
    finally:
        # Stop the session
        session.stop()
Ejemplo n.º 11
0
def main():
    """Main function"""

    options = parseCmdLine()

    # Fill SessionOptions
    sessionOptions = prepareZfpSessionOptions(options) \
        if options.remote \
        else prepareStandardSessionOptions(options)
    sessionOptions.setSessionIdentityOptions(options.auth['option'])
    sessionOptions.setAutoRestartOnDisconnection(True)

    myEventHandler = MyEventHandler()

    # Create a Session
    session = blpapi.ProviderSession(sessionOptions,
                                     myEventHandler.processEvent)

    # Start a Session
    if not session.start():
        print("Failed to start session.")
        return

    topicList = blpapi.TopicList()
    topicList.add(options.service + options.topic,
                  blpapi.CorrelationId(MyStream(options.topic)))

    # Create topics
    session.createTopics(topicList,
                         blpapi.ProviderSession.AUTO_REGISTER_SERVICES)
    # createTopics() is synchronous, topicList will be updated
    # with the results of topic creation (resolution will happen
    # under the covers)

    streams = []
    for i in range(topicList.size()):
        stream = topicList.correlationIdAt(i).value()
        status = topicList.statusAt(i)

        if status == blpapi.TopicList.CREATED:
            stream.topic = session.getTopic(topicList.messageAt(i))
            streams.append(stream)
        else:
            print("Stream '%s': topic not resolved, status = %d" %
                  (stream.id, status))

    service = session.getService(options.service)

    try:
        # Now we will start publishing
        while streams and g_running:
            event = service.createPublishEvent()
            eventFormatter = blpapi.EventFormatter(event)

            for stream in streams:
                eventFormatter.appendMessage("PageData", stream.topic)
                eventFormatter.pushElement("rowUpdate")

                eventFormatter.appendElement()
                eventFormatter.setElement("rowNum", 1)
                eventFormatter.pushElement("spanUpdate")

                eventFormatter.appendElement()
                eventFormatter.setElement("startCol", 20)
                eventFormatter.setElement("length", 4)
                eventFormatter.setElement("text", "TEST")
                eventFormatter.popElement()

                eventFormatter.appendElement()
                eventFormatter.setElement("startCol", 25)
                eventFormatter.setElement("length", 4)
                eventFormatter.setElement("text", "PAGE")
                eventFormatter.popElement()

                tm = time.strftime("%X")
                eventFormatter.appendElement()
                eventFormatter.setElement("startCol", 30)
                eventFormatter.setElement("length", len(tm))
                eventFormatter.setElement("text", tm)
                eventFormatter.setElement("attr", "BLINK")
                eventFormatter.popElement()

                eventFormatter.popElement()
                eventFormatter.popElement()

                eventFormatter.appendElement()
                eventFormatter.setElement("rowNum", 2)
                eventFormatter.pushElement("spanUpdate")
                eventFormatter.appendElement()
                eventFormatter.setElement("startCol", 20)
                eventFormatter.setElement("length", 9)
                eventFormatter.setElement("text", "---------")
                eventFormatter.setElement("attr", "UNDERLINE")
                eventFormatter.popElement()
                eventFormatter.popElement()
                eventFormatter.popElement()

                eventFormatter.appendElement()
                eventFormatter.setElement("rowNum", 3)
                eventFormatter.pushElement("spanUpdate")
                eventFormatter.appendElement()
                eventFormatter.setElement("startCol", 10)
                eventFormatter.setElement("length", 9)
                eventFormatter.setElement("text", "TEST LINE")
                eventFormatter.popElement()
                eventFormatter.appendElement()
                eventFormatter.setElement("startCol", 23)
                eventFormatter.setElement("length", 5)
                eventFormatter.setElement("text", "THREE")
                eventFormatter.popElement()
                eventFormatter.popElement()
                eventFormatter.popElement()
                eventFormatter.popElement()

                eventFormatter.setElement("contributorId",
                                          options.contributorId)
                eventFormatter.setElement("productCode", 1)
                eventFormatter.setElement("pageNumber", 1)

            for msg in event:
                print(msg)

            session.publish(event)
            time.sleep(10)
    finally:
        # Stop the session
        session.stop()