Beispiel #1
0
def createEventFileSettings(tree, files):
    fileid = 0
    sysconfig = """
$ModLoad imfile

                """
    if not files:
        return
    for file in files:
        fileid = fileid + 1
        eventSourceElement = XmlUtil.createElement(eventSourceSchema)
        XmlUtil.setXmlValue(eventSourceElement, 'RouteEvent', 'eventName',
                            file["table"])
        eventSourceElement.set('source', 'ladfile' + str(fileid))
        XmlUtil.addElement(tree, 'Events/MdsdEvents', eventSourceElement)

        sourceElement = XmlUtil.createElement(sourceSchema)
        sourceElement.set('name', 'ladfile' + str(fileid))
        XmlUtil.addElement(tree, 'Sources', sourceElement)

        syslog_config = syslogEventSourceConfig.replace('#FILE#', file['file'])
        syslog_config = syslog_config.replace('#STATFILE#',
                                              file['file'].replace("/", "-"))
        syslog_config = syslog_config.replace('#FILETAG#',
                                              'ladfile' + str(fileid))
        sysconfig += syslog_config
    return sysconfig
    def _update_perf_counters_settings(self, omi_queries, for_app_insights=False):
        """
        Update the mdsd XML tree with the OMI queries provided.
        :param omi_queries: List of dictionaries specifying OMI queries and destination tables. E.g.:
         [
             {"query":"SELECT PercentAvailableMemory, AvailableMemory, UsedMemory, PercentUsedSwap FROM SCX_MemoryStatisticalInformation","table":"LinuxMemory"},
             {"query":"SELECT PercentProcessorTime, PercentIOWaitTime, PercentIdleTime FROM SCX_ProcessorStatisticalInformation WHERE Name='_TOTAL'","table":"LinuxCpu"},
             {"query":"SELECT AverageWriteTime,AverageReadTime,ReadBytesPerSecond,WriteBytesPerSecond FROM  SCX_DiskDriveStatisticalInformation WHERE Name='_TOTAL'","table":"LinuxDisk"}
         ]
        :param for_app_insights: Indicates whether we are updating perf counters settings for AppInsights.
                                AppInsights requires specific names, so we need this.
        :return: None. The mdsd XML tree member is updated accordingly.
        """
        assert self._mdsd_config_xml_tree is not None

        if not omi_queries:
            return

        mdsd_omi_query_schema = """
<OMIQuery cqlQuery="" dontUsePerNDayTable="true" eventName="" omiNamespace="" priority="High" sampleRateInSeconds="" />
"""

        for omi_query in omi_queries:
            mdsd_omi_query_element = XmlUtil.createElement(mdsd_omi_query_schema)
            mdsd_omi_query_element.set('cqlQuery', omi_query['query'])
            mdsd_omi_query_element.set('eventName', omi_query['table'])
            namespace = omi_query['namespace'] if 'namespace' in omi_query else 'root/scx'
            mdsd_omi_query_element.set('omiNamespace', namespace)
            if for_app_insights:
                AIUtil.updateOMIQueryElement(mdsd_omi_query_element)
            XmlUtil.addElement(xml=self._mdsd_config_xml_tree, path='Events/OMI', el=mdsd_omi_query_element, addOnlyOnce=True)
Beispiel #3
0
def createPortalSettings(tree, resourceId):
    portal_config = ET.ElementTree()
    portal_config.parse(os.path.join(WorkDir, "portal.xml.template"))
    XmlUtil.setXmlValue(portal_config, "./DerivedEvents/DerivedEvent/LADQuery",
                        "partitionKey", resourceId)
    XmlUtil.addElement(tree, 'Events', portal_config._root.getchildren()[0])
    XmlUtil.addElement(tree, 'Events', portal_config._root.getchildren()[1])
 def _add_element_from_element(self, path, xml_elem, add_only_once=True):
     """
     Add an XML fragment to the mdsd config document in accordance with path
     :param str path: Where to add the fragment
     :param ElementTree xml_elem: An ElementTree object XML fragment that should be added to the path.
     :param bool add_only_once: Indicates whether to perform the addition only to the first match of the path.
     """
     XmlUtil.addElement(xml=self._mdsd_config_xml_tree, path=path, el=xml_elem, addOnlyOnce=add_only_once)
 def _add_element_from_element(self, path, xml_elem, add_only_once=True):
     """
     Add an XML fragment to the mdsd config document in accordance with path
     :param str path: Where to add the fragment
     :param ElementTree xml_elem: An ElementTree object XML fragment that should be added to the path.
     :param bool add_only_once: Indicates whether to perform the addition only to the first match of the path.
     """
     XmlUtil.addElement(xml=self._mdsd_config_xml_tree, path=path, el=xml_elem, addOnlyOnce=add_only_once)
    def _update_and_get_file_monitoring_settings(self, files):
        """
        Update mdsd config's file monitoring config. Also creates/returns rsyslog imfile config.
        All the operations are based on the input param files, which is a Json-deserialized dictionary
        corresponding the following Json array example:
        [
            {"file":"/var/log/a.log", "table":"aLog"},
            {"file":"/var/log/b.log", "table":"bLog"}
        ]
        :param files: Array of dictionaries deserialized from the 'fileCfg' Json config (example as above)
        :return: rsyslog omfile module config file content
        """
        assert self._mdsd_config_xml_tree is not None

        if not files:
            return ''

        file_id = 0
        imfile_config = """
$ModLoad imfile

"""

        mdsd_event_source_schema = """
<MdsdEventSource source="ladfile">
    <RouteEvent dontUsePerNDayTable="true" eventName="" priority="High"/>
</MdsdEventSource>
"""

        mdsd_source_schema = """
<Source name="ladfile1" schema="ladfile" />
"""
        imfile_per_file_config_template = """
$InputFileName #FILE#
$InputFileTag #FILETAG#
$InputFileFacility local6
$InputFileStateFile syslog-stat#STATFILE#
$InputFileSeverity debug
$InputRunFileMonitor
"""

        for item in files:
            file_id += 1
            mdsd_event_source_element = XmlUtil.createElement(mdsd_event_source_schema)
            XmlUtil.setXmlValue(mdsd_event_source_element, 'RouteEvent', 'eventName', item["table"])
            mdsd_event_source_element.set('source', 'ladfile'+str(file_id))
            XmlUtil.addElement(self._mdsd_config_xml_tree, 'Events/MdsdEvents', mdsd_event_source_element)

            mdsd_source_element = XmlUtil.createElement(mdsd_source_schema)
            mdsd_source_element.set('name', 'ladfile'+str(file_id))
            XmlUtil.addElement(self._mdsd_config_xml_tree, 'Sources', mdsd_source_element)

            imfile_per_file_config = imfile_per_file_config_template.replace('#FILE#', item['file'])
            imfile_per_file_config = imfile_per_file_config.replace('#STATFILE#', item['file'].replace("/","-"))
            imfile_per_file_config = imfile_per_file_config.replace('#FILETAG#', 'ladfile'+str(file_id))
            imfile_config += imfile_per_file_config
        return imfile_config
 def _add_element_from_string(self, path, xml_string, add_only_once=True):
     """
     Add an XML fragment to the mdsd config document in accordance with path
     :param str path: Where to add the fragment
     :param str xml_string: A string containing the XML element to add
     :param bool add_only_once: Indicates whether to perform the addition only to the first match of the path.
     """
     XmlUtil.addElement(xml=self._mdsd_config_xml_tree, path=path, el=ET.fromstring(xml_string),
                        addOnlyOnce=add_only_once)
 def _add_element_from_string(self, path, xml_string, add_only_once=True):
     """
     Add an XML fragment to the mdsd config document in accordance with path
     :param str path: Where to add the fragment
     :param str xml_string: A string containing the XML element to add
     :param bool add_only_once: Indicates whether to perform the addition only to the first match of the path.
     """
     XmlUtil.addElement(xml=self._mdsd_config_xml_tree, path=path, el=ET.fromstring(xml_string),
                        addOnlyOnce=add_only_once)
def createPerfSettngs(tree,perfs,forAI=False):
    if not perfs:
        return
    for perf in perfs:
        perfElement = XmlUtil.createElement(perfSchema)
        perfElement.set('cqlQuery',perf['query'])
        perfElement.set('eventName',perf['table'])
        namespace="root/scx"
        if perf.has_key('namespace'):
           namespace=perf['namespace']
        perfElement.set('omiNamespace',namespace)
        if forAI:
            AIUtil.updateOMIQueryElement(perfElement)
        XmlUtil.addElement(tree,'Events/OMI',perfElement,["omitag","perf"])
 def _add_derived_event(self, interval, source, event_name, store_type, add_lad_query=False):
     """
     Add a <DerivedEvent> element to the configuration
     :param str interval: Interval at which this DerivedEvent should be run 
     :param str source: Local table from which this DerivedEvent should pull
     :param str event_name: Destination table to which this DerivedEvent should push
     :param str store_type: The storage type of the destination table, e.g. Local, Central, JsonBlob
     :param bool add_lad_query: True if a <LadQuery> subelement should be added to this <DerivedEvent> element
     """
     derived_event = mxt.derived_event.format(interval=interval, source=source, target=event_name, type=store_type)
     element = ET.fromstring(derived_event)
     if add_lad_query:
         XmlUtil.addElement(element, ".", ET.fromstring(mxt.lad_query))
     self._add_element_from_element('Events/DerivedEvents', element)
 def _add_derived_event(self, interval, source, event_name, store_type, add_lad_query=False):
     """
     Add a <DerivedEvent> element to the configuration
     :param str interval: Interval at which this DerivedEvent should be run 
     :param str source: Local table from which this DerivedEvent should pull
     :param str event_name: Destination table to which this DerivedEvent should push
     :param str store_type: The storage type of the destination table, e.g. Local, Central, JsonBlob
     :param bool add_lad_query: True if a <LadQuery> subelement should be added to this <DerivedEvent> element
     """
     derived_event = mxt.derived_event.format(interval=interval, source=source, target=event_name, type=store_type)
     element = ET.fromstring(derived_event)
     if add_lad_query:
         XmlUtil.addElement(element, ".", ET.fromstring(mxt.lad_query))
     self._add_element_from_element('Events/DerivedEvents', element)
def createPerfSettngs(tree, perfs, forAI=False):
    if not perfs:
        return
    for perf in perfs:
        perfElement = XmlUtil.createElement(perfSchema)
        perfElement.set("cqlQuery", perf["query"])
        perfElement.set("eventName", perf["table"])
        namespace = "root/scx"
        if perf.has_key("namespace"):
            namespace = perf["namespace"]
        perfElement.set("omiNamespace", namespace)
        if forAI:
            AIUtil.updateOMIQueryElement(perfElement)
        XmlUtil.addElement(tree, "Events/OMI", perfElement, ["omitag", "perf"])
    def _add_portal_settings(self, resource_id):
        """
        Update mdsd_config_xml_tree for Azure Portal metric collection setting.
        It's basically applying the resource_id as the partitionKey attribute of LADQuery elements.

        :param resource_id: ARM rerousce ID to provide as partitionKey in LADQuery elements
        :return: None
        """
        assert self._mdsd_config_xml_tree is not None

        portal_config = ET.ElementTree()
        portal_config.parse(os.path.join(self._ext_dir, 'portal.xml.template'))
        XmlUtil.setXmlValue(portal_config, './DerivedEvents/DerivedEvent/LADQuery', 'partitionKey', resource_id)
        XmlUtil.addElement(self._mdsd_config_xml_tree, 'Events', portal_config._root.getchildren()[0])
        XmlUtil.addElement(self._mdsd_config_xml_tree, 'Events', portal_config._root.getchildren()[1])
Beispiel #14
0
def UpdateXML(doc):
    """
    Add to the mdsd XML the minimal set of OMI queries which will retrieve the metrics requested via AddMetric(). This
    provider doesn't need any configuration external to mdsd; if it did, that would be generated here as well.

    :param doc: XML document object to be updated
    :return: None
    """
    global _metrics, _eventNames, _omiClassName
    for group in _metrics:
        (class_name, condition_clause, sample_rate) = group
        if not condition_clause:
            condition_clause = default_condition(class_name)
        columns = []
        mappings = []
        for metric in _metrics[group]:
            omi_name = metric.counter_name()
            scale = _scaling[class_name][omi_name]
            columns.append(omi_name)
            mappings.append('<MapName name="{0}" {1}>{2}</MapName>'.format(
                omi_name, scale, metric.label()))
        column_string = ','.join(columns)
        if condition_clause:
            cql_query = quoteattr("SELECT {0} FROM {1} WHERE {2}".format(
                column_string, _omiClassName[class_name], condition_clause))
        else:
            cql_query = quoteattr("SELECT {0} FROM {1}".format(
                column_string, _omiClassName[class_name]))
        query = '''
<OMIQuery cqlQuery={qry} eventName={evname} omiNamespace="root/scx" sampleRateInSeconds="{rate}" storeType="local">
  <Unpivot columnName="CounterName" columnValue="Value" columns={columns}>
    {mappings}
  </Unpivot>
</OMIQuery>'''.format(qry=cql_query,
                      evname=quoteattr(_eventNames[group]),
                      columns=quoteattr(column_string),
                      rate=sample_rate,
                      mappings='\n    '.join(mappings))
        XmlUtil.addElement(doc, 'Events/OMI', ET.fromstring(query))
    return
Beispiel #15
0
def UpdateXML(doc):
    """
    Add to the mdsd XML the minimal set of OMI queries which will retrieve the metrics requested via AddMetric(). This
    provider doesn't need any configuration external to mdsd; if it did, that would be generated here as well.

    :param doc: XML document object to be updated
    :return: None
    """
    global _metrics, _eventNames, _omiClassName
    for group in _metrics:
        (class_name, condition_clause, sample_rate) = group
        if not condition_clause:
            condition_clause = default_condition(class_name)
        columns = []
        mappings = []
        for metric in _metrics[group]:
            omi_name = metric.counter_name()
            scale = _scaling[class_name][omi_name]
            columns.append(omi_name)
            mappings.append('<MapName name="{0}" {1}>{2}</MapName>'.format(omi_name, scale, metric.label()))
        column_string = ','.join(columns)
        if condition_clause:
            cql_query = quoteattr("SELECT {0} FROM {1} WHERE {2}".format(column_string,
                                                                         _omiClassName[class_name], condition_clause))
        else:
            cql_query = quoteattr("SELECT {0} FROM {1}".format(column_string, _omiClassName[class_name]))
        query = '''
<OMIQuery cqlQuery={qry} eventName={evname} omiNamespace="root/scx" sampleRateInSeconds="{rate}" storeType="local">
  <Unpivot columnName="CounterName" columnValue="Value" columns={columns}>
    {mappings}
  </Unpivot>
</OMIQuery>'''.format(
            qry=cql_query,
            evname=quoteattr(_eventNames[group]),
            columns=quoteattr(column_string),
            rate=sample_rate,
            mappings='\n    '.join(mappings)
        )
        XmlUtil.addElement(doc, 'Events/OMI', ET.fromstring(query))
    return
def createEventFileSettings(tree, files):
    fileid = 0
    sysconfig = """
$ModLoad imfile

                """
    if not files:
        return
    for file in files:
        fileid = fileid + 1
        eventSourceElement = XmlUtil.createElement(eventSourceSchema)
        XmlUtil.setXmlValue(eventSourceElement, "RouteEvent", "eventName", file["table"])
        eventSourceElement.set("source", "ladfile" + str(fileid))
        XmlUtil.addElement(tree, "Events/MdsdEvents", eventSourceElement)

        sourceElement = XmlUtil.createElement(sourceSchema)
        sourceElement.set("name", "ladfile" + str(fileid))
        XmlUtil.addElement(tree, "Sources", sourceElement)

        syslog_config = syslogEventSourceConfig.replace("#FILE#", file["file"])
        syslog_config = syslog_config.replace("#STATFILE#", file["file"].replace("/", "-"))
        syslog_config = syslog_config.replace("#FILETAG#", "ladfile" + str(fileid))
        sysconfig += syslog_config
    return sysconfig
def createEventFileSettings(tree,files):
    fileid = 0;
    sysconfig = """
$ModLoad imfile

                """
    if not files:
        return
    for file in files:
        fileid=fileid+1
        eventSourceElement = XmlUtil.createElement(eventSourceSchema)
        XmlUtil.setXmlValue(eventSourceElement,'RouteEvent','eventName',file["table"])
        eventSourceElement.set('source','ladfile'+str(fileid))
        XmlUtil.addElement(tree,'Events/MdsdEvents',eventSourceElement)

        sourceElement = XmlUtil.createElement(sourceSchema)
        sourceElement.set('name','ladfile'+str(fileid))
        XmlUtil.addElement(tree,'Sources',sourceElement)

        syslog_config = syslogEventSourceConfig.replace('#FILE#',file['file'])
        syslog_config = syslog_config.replace('#STATFILE#',file['file'].replace("/","-"))
        syslog_config = syslog_config.replace('#FILETAG#','ladfile'+str(fileid))
        sysconfig+=syslog_config
    return sysconfig
def createPortalSettings(tree,resourceId):
    portal_config = ET.ElementTree()
    portal_config.parse(os.path.join(WorkDir, "portal.xml.template"))
    XmlUtil.setXmlValue(portal_config,"./DerivedEvents/DerivedEvent/LADQuery","partitionKey",resourceId)
    XmlUtil.addElement(tree,'Events',portal_config._root.getchildren()[0])
    XmlUtil.addElement(tree,'Events',portal_config._root.getchildren()[1])
Beispiel #19
0
    def addChildrenLayout(self, element, rectView, parentLeft, parentTop,
                          rectViewElementInfoMap):
        # Setting background

        for childRectView in rectView.mChildren:
            _id = ""
            # list view has it own index

            _id = self.getId(LayoutHelper.FRAMELAYOUT_ELEMENT)
            marginLeft = childRectView.x
            marginTop = childRectView.y
            childElement = None
            childElement = XmlUtil.addElement(
                self.mDipCalculator, element,
                self.getElementTypeForRect(childRectView), childRectView,
                marginLeft, marginTop, _id, self.mColorWriter)

            rectViewElementInfoMap[childRectView] = ElementInfo(
                childElement, _id)
            self.addChildrenLayout(childElement, childRectView,
                                   childRectView.x, childRectView.y,
                                   rectViewElementInfoMap)

        XmlUtil.addBackgroundColor(element, rectView.mColor, self.mColorWriter)

        if (rectView == self.mRootView):
            pass

        # if children is icon add this attributes for code generation
        elif (rectView.isIconButton()):
            iconButtonName = rectView.getIconName()
            elementID = rectView.getElementID()
            element.tag = Constants.ELEMENT_IMAGE_BUTTON
            XmlUtil.addImageDrawable(element, iconButtonName)
            _id = self.getId(Constants.ELEMENT_IMAGE_BUTTON)

            # fit it to center
            XmlUtil.addAdditionalAttribute(element, "android:scaleType",
                                           "fitCenter")

            # add press animation
            XmlUtil.addAdditionalAttribute(element, "android:background",
                                           "@drawable/oniconpress")

            rectViewElementInfoMap[rectView] = ElementInfo(element, elementID)

        # if children is text add this attributes for code generation
        elif (rectView.isText()):
            # default text hello text
            helloText = "Hello Text"
            stringId = self.mWriter.addResource(helloText)
            element.tag = Constants.ELEMENT_TEXT_VIEW

            XmlUtil.addSize(self.mDipCalculator, element, rectView.width,
                            rectView.height)

            XmlUtil.addBackgroundColor(element, rectView.mColor,
                                       self.mColorWriter)
            element.set(Constants.ATTRIBUTE_TEXT,
                        XmlUtil.getReferenceResourceId(stringId))
            _id = self.getId(Constants.ELEMENT_TEXT_VIEW)
            XmlUtil.addId(element, _id)
            color = ColorUtil.cColortoInt(CColor.Black)
            XmlUtil.addTextColor(element, color, self.mColorWriter)
            # Set the auto text size property
            element.set(Constants.ATTRIBUTE_AUTOSIZE_TEXT_TYPE, "uniform")
            rectViewElementInfoMap[rectView] = ElementInfo(element, _id)

        # for all other UI elements
        else:
            # for checkbox
            if (rectView.isCheckbox()):
                _id = self.getId(Constants.ELEMENT_CHECK_BOX)
                element.tag = Constants.ELEMENT_CHECK_BOX
                # set checkbox default to uncheck
                XmlUtil.addAdditionalAttribute(element, "android:button",
                                               "@null")
                XmlUtil.addAdditionalAttribute(element, "app:theme",
                                               "@style/CheckboxStyle")
                XmlUtil.addAdditionalAttribute(
                    element, "android:background",
                    "?android:attr/listChoiceIndicatorMultiple")

                # for Toggle
            elif (rectView.isToogle()):
                element.tag = Constants.ELEMENT_SWITCH
                _id = self.getId(Constants.ELEMENT_SWITCH)
                minWidthDp = str(
                    self.mDipCalculator.pxToWidthDip(rectView.width) -
                    12) + Constants.UNIT_DIP
                XmlUtil.addAttribute(element, "android:switchMinWidth",
                                     minWidthDp)

            # for Slider
            elif (rectView.isSlider()):
                element.tag = Constants.ELEMENT_SEEK_BAR
                color = ColorUtil.cColortoInt(CColor.Black)
                XmlUtil.addAttributeColor(element, "android:progressTint",
                                          color, self.mColorWriter)
                XmlUtil.addAttributeColor(element, "android:thumbTint", color,
                                          self.mColorWriter)
                _id = self.getId(Constants.ELEMENT_SEEK_BAR)
                XmlUtil.addBackgroundColor(element, rectView.mColor,
                                           self.mColorWriter)

            # for star convert it to raing
            elif (rectView.isRating()):

                element.tag = Constants.ELEMENT_RATING_BAR
                XmlUtil.addAttribute(element, "android:layout_width",
                                     "wrap_content")
                XmlUtil.addAttribute(element, "android:layout_height",
                                     "wrap_content")
                XmlUtil.addAttribute(element, "android:theme",
                                     "@style/RatingBar")
                # based on the width of the element set number of star in rating
                widthOfStar = int(
                    self.mDipCalculator.pxToWidthDip(rectView.width) / 50)
                _id = self.getId(Constants.ELEMENT_RATING_BAR)
                XmlUtil.addAttribute(element, "android:numStars",
                                     str(widthOfStar))

            # for Searchbar
            elif (rectView.isSearchBar()):
                element.tag = Constants.ELEMENT_SEARCH_BAR
                _id = self.getId(Constants.ELEMENT_SEARCH_BAR)
                XmlUtil.addBackgroundColor(element, rectView.mColor,
                                           self.mColorWriter)

            # for Searchbar
            elif (rectView.isUserImage()):
                element.tag = Constants.ELEMENT_IMAGE_VIEW
                iconButtonName = "userimage"
                XmlUtil.addImageDrawable(element, iconButtonName)
                _id = self.getId(Constants.ELEMENT_IMAGE_VIEW)

                # for Container
            elif (rectView.isContainer()):
                XmlUtil.addAttribute(element, "android:background",
                                     "@drawable/border")
                _id = self.getId(LayoutHelper.FRAMELAYOUT_ELEMENT)

                # for Dropdown
            elif (rectView.isDropDown()):
                element.tag = Constants.ELEMENT_SPINNER
                XmlUtil.addAdditionalAttribute(element,
                                               "android:drawSelectorOnTop",
                                               "true")
                arrayId = self.mWriter.addArrayResource("default")
                # create a dummy array for the dropdown
                element.set(Constants.ATTRIBUTE_DROPDOWN_ENTRIES,
                            XmlUtil.getArrayReferenceResourceId(arrayId))
                _id = self.getId(Constants.ELEMENT_SPINNER)
                element.attrib.pop("android:background", None)

                # for Text Button
            elif (rectView.isButtonText()):
                element.tag = Constants.ELEMENT_BUTTON
                XmlUtil.addAdditionalAttribute(element, "android:text",
                                               "Button")
                _id = self.getId(Constants.ELEMENT_BUTTON)
                XmlUtil.addAdditionalAttribute(element, "android:background",
                                               "@drawable/oniconpress")

            XmlUtil.addId(element, _id)

            rectViewElementInfoMap[rectView] = ElementInfo(element, _id)
def createSyslogRouteEventElement(mdsdCfg):
    aiSyslogRouteEvent = XmlUtil.createElement("<RouteEvent eventName=\"aiSyslogRouteEvent\" priority=\"High\" account=\"appinsights\" storeType=\"appinsights\"/>");
    XmlUtil.addElement(mdsdCfg,'Events/MdsdEvents/MdsdEventSource',aiSyslogRouteEvent,['source','syslog'])
def createAccountElement(mdsdCfg, aikey):
    aiAccountElement = XmlUtil.createElement("<Account moniker=\"appinsights\" appInsightsKey=\"" + aikey + "\"/>");
    XmlUtil.addElement(mdsdCfg,'Accounts',aiAccountElement)
Beispiel #22
0
    def addChildrenLayout(self, element, rectView, parentLeft, parentTop,
                          rectViewElementInfoMap):
        # Setting background
        if (self.useTransparentBackground(rectView)):
            XmlUtil.addBackgroundColor(element,
                                       ColorUtil.toInt(0, 255, 255, 255),
                                       self.mColorWriter)
#        elif (RectViewTypes.isContanerView(rectView)) :
# We always want to genenate background regard less of the respect
# ratioand Environment.get().getValue(Environment.KEY_KEEP_ASPECT_RATIO) == Boolean.TRUE
# We will not do this if ratio is between input image and output is the same
#            bound = ImageUtil.getImageFromRect(self.mImage, rectView)
#            # We remove children here using 4 layer channel So we have to make sure that when we save it we will not Adding anymore layer
#            newImageBackground = ImageUtil.removeChildren(bound, rectView)
#            drawableId = self.mDrawableWriter.addResourceDirectly(newImageBackground, rectView)
#            XmlUtil.addBackroundImage(element, drawableId)

        else:
            XmlUtil.addBackgroundColor(element, rectView.mColor,
                                       self.mColorWriter)

        for childRectView in rectView.mChildren:
            _id = ""
            # list view has it own index
            if (childRectView.mType == RectViewTypes.VIEW_TYPE_LIST):
                _id = childRectView.mListInfo.xmlId
            else:
                _id = self.getId(LayoutHelper.FRAMELAYOUT_ELEMENT,
                                 childRectView)

            marginLeft = childRectView.x - parentLeft
            marginTop = childRectView.y - parentTop
            childElement = None
            if (self.useTransparentBackground(childRectView)):
                childElement = XmlUtil.addElement(
                    self.mDipCalculator, element,
                    self.getElementTypeForRect(childRectView), childRectView,
                    marginLeft, marginTop, _id)
            else:
                childElement = XmlUtil.addElement(
                    self.mDipCalculator, element,
                    self.getElementTypeForRect(childRectView), childRectView,
                    marginLeft, marginTop, _id, self.mColorWriter)

            rectViewElementInfoMap[childRectView] = ElementInfo(
                childElement, _id)
            self.addChildrenLayout(childElement, childRectView,
                                   childRectView.x, childRectView.y,
                                   rectViewElementInfoMap)

        # image view
        if (rectView.mType == RectViewTypes.VIEW_TYPE_IMAGE):
            drawableId = self.interestedIcons.get(rectView.mImageInfo.iconInfo)
            element.tag = Constants.ELEMENT_IMAGE_VIEW
            XmlUtil.addImageDrawable(element, drawableId)
            # override attributes
            XmlUtil.removeAttribute(element, Constants.ATTRIBUTE_BACKGROUND)
            _id = self.getId(Constants.ELEMENT_IMAGE_VIEW, rectView)
            XmlUtil.addId(element, _id)
            XmlUtil.addScaleType(element, "fitXY")
            rectViewElementInfoMap[rectView] = ElementInfo(element, _id)
        elif (rectView.mType == RectViewTypes.VIEW_TYPE_TEXT):

            textWrapper = rectView.mTextInfo.textWrapper
            stringId = self.mWriter.addResource(textWrapper.text)
            rectView.mTextInfo._id = stringId
            element.tag = Constants.ELEMENT_TEXT_VIEW
            if (Environment.getValue(
                    Environment.KEY_TEXT_WIDTH_WRAP_CONTENT) == True):
                XmlUtil.addSize(self.mDipCalculator, element,
                                Constants.ATTRIBUTE_WRAP_CONTENT,
                                rectView.height)
            else:
                XmlUtil.addSize(self.mDipCalculator, element, rectView.width,
                                rectView.height)

            XmlUtil.addBackgroundColor(element, rectView.mColor,
                                       self.mColorWriter)
            element.set(Constants.ATTRIBUTE_TEXT,
                        XmlUtil.getReferenceResourceId(stringId))
            _id = self.getId(Constants.ELEMENT_TEXT_VIEW, rectView)
            XmlUtil.addId(element, _id)
            textAttributes = textWrapper.getTextAttributes(
                self.mOcr, rectView.height)
            XmlUtil.addTextColor(element, rectView.textColor,
                                 self.mColorWriter)
            stypeId = self.mStyleWriter.addResource(textAttributes)
            element.set(Constants.ATTRIBUTE_STYLE,
                        XmlUtil.getReferenceStyleId(stypeId))
            rectViewElementInfoMap[rectView] = ElementInfo(element, _id)
def createSyslogRouteEventElement(mdsdCfg):
    aiSyslogRouteEvent = XmlUtil.createElement(
        "<RouteEvent eventName=\"aiSyslogRouteEvent\" priority=\"High\" account=\"appinsights\" storeType=\"appinsights\"/>"
    )
    XmlUtil.addElement(mdsdCfg, 'Events/MdsdEvents/MdsdEventSource',
                       aiSyslogRouteEvent, ['source', 'syslog'])
def createAccountElement(mdsdCfg, aikey):
    aiAccountElement = XmlUtil.createElement(
        "<Account moniker=\"appinsights\" appInsightsKey=\"" + aikey + "\"/>")
    XmlUtil.addElement(mdsdCfg, 'Accounts', aiAccountElement)