Пример #1
0
 def test_object_varargs(self):
     "array.array objects can be used in the varargs position, with primitive boxing"
     a = array('i', range(5, 10))
     self.assertEqual(
         'arg 0=5, arg 1=6, arg 2=7, arg 3=8, arg 4=9',
         JString.format('arg 0=%d, arg 1=%d, arg 2=%d, arg 3=%d, arg 4=%d',
                        [5, 6, 7, 8, 9]))
Пример #2
0
 def test_object_varargs(self):
     "array.array objects can be used in the varargs position, with primitive boxing"
     a = array("i", range(5, 10))
     self.assertEqual(
         "arg 0=5, arg 1=6, arg 2=7, arg 3=8, arg 4=9",
         JString.format("arg 0=%d, arg 1=%d, arg 2=%d, arg 3=%d, arg 4=%d", [5, 6, 7, 8, 9]),
     )
Пример #3
0
    def __createNew(self):
        self.vc("log").debug("Creating a new package...")
        packageType, jsonConfigFile = self.__getPackageTypeAndJsonConfigFile()
        self.vc("log").debug("packageType = '{}'", packageType)
        self.vc("log").debug("jsonConfigFile = '{}'", jsonConfigFile)

        manifestHash = "%s.tfpackage" % uuid.uuid4()
        # store the manifest file for harvesting
        packageDir = FascinatorHome.getPathFile("packages")
        packageDir.mkdirs()
        manifestFile = File(packageDir, manifestHash)
        outStream = FileOutputStream(manifestFile)
        outWriter = OutputStreamWriter(outStream, "UTF-8")

        self.vc("sessionState").set("package/active", None)
        manifest = self.__getActiveManifest()
        manifest.setType(packageType)
        metaList = list(self.vc("formData").getValues("metaList"))
        jsonObj = manifest.getJsonObject()
        for metaName in metaList:
            value = self.vc("formData").get(metaName)
            jsonObj.put(metaName, value)
        if self.vc("formData").getValues("sequencesMetaList") != None:    
            sequenceService = ApplicationContextProvider.getApplicationContext().getBean("sequenceService")
            sequencesMetaList = list(self.vc("formData").getValues("sequencesMetaList"))
            for sequenceInfo in sequencesMetaList:   
                sequenceInfoJson = JsonSimple(sequenceInfo)
                sequenceIndex = sequenceService.getSequence(sequenceInfoJson.getString(None,"sequenceName"))
                jsonObj.put(sequenceInfoJson.getString(None,"metadataName"), String.format(sequenceInfoJson.getString(None,"stringFormat"),sequenceIndex))
        self.vc("log").debug("json object created is: %r" % jsonObj)
        outWriter.write(manifest.toString(True))
        outWriter.close()
        # adding ability to set access plugin
        accessPlugin = self.vc("formData").get("access_plugin", "derby")
        if accessPlugin is not None:
            self.vc("page").authentication.set_access_plugin(accessPlugin)
        try:
            # harvest the package as an object
            username = self.vc("sessionState").get("username")
            if username is None:
                username = "******" # necessary?
            harvester = None
            # set up config files, creating if necessary
            workflowsDir = FascinatorHome.getPathFile("harvest/workflows")
            configFile = self.__getFile(workflowsDir, jsonConfigFile)
            self.__getFile(workflowsDir, "packaging-rules.py")
            # run the harvest client with our packaging workflow config
            harvester = HarvestClient(configFile, manifestFile, username)
            harvester.start()
            manifestId = harvester.getUploadOid()
            harvester.shutdown()
        except Exception, ex:
            error = "Packager workflow failed: %s" % str(ex)
            self.vc("log").error(error, ex)
            if harvester is not None:
                harvester.shutdown()
            return '{ "status": "failed" }'
Пример #4
0
def testFormat():
    dataManager = DALLocator.getDataManager()
    ws = dataManager.getDatabaseWorkspace("ARENA2_DB")
    server = ws.getServerExplorer()
    accidentesParameters = server.get("ARENA2_ACCIDENTES")
    dataManager = DALLocator.getDataManager()
    store = dataManager.openStore(accidentesParameters.getProviderName(),
                                  accidentesParameters)
    ft = store.getDefaultFeatureType()
    ehora = ft.getAttributeDescriptor("HORA_ACCIDENTE")
    ekm = ft.getAttributeDescriptor("KM")
    from java.sql import Timestamp
    from java.util import Date
    ts = Timestamp(Date().getTime())
    print ehora.format(ts)

    print ekm.format(10.282999895)
    from java.lang import String
    print String.format("%.3f", 10.39283)
    print String.format("%tR", Timestamp(Date().getTime()))
Пример #5
0
 def wrapper(ctx):
     response = func(context=ctx,
                     logString=test_name,
                     template=test_name + ".vm")
     stats = grinder.statistics.getForCurrentTest()
     if maximum and stats.time > maximum:
         grinder.getLogger().error(
             String.format(
                 Locale.ENGLISH,
                 "Request took too long (%s ms), while maximum was %s ms",
                 [stats.time, maximum]))
         stats.success = 0
Пример #6
0
    def notifyExternalRelationship(self, relationship,pid,system,identifier):
        try:
            url = self.systemConfig.getString(None, "curation","external-system-urls","notify-curation",system)
            self.writer.println(url+ "&relationship=isCollectedBy&curatedPid="+pid+"&identifier="+relationship.get("identifier")+"&system="+self.systemConfig.getString(None,"system")+"&sourceIdentifier="+identifier)
            client = BasicHttpClient(url+ "&relationship=isCollectedBy&curatedPid="+pid+"&identifier="+relationship.get("identifier")+"&system="+self.systemConfig.getString(None,"system")+"&sourceIdentifier="+identifier)
            get = GetMethod(url+ "&relationship=isCollectedBy&curatedPid="+pid+"&identifier="+relationship.get("identifier")+"&system="+self.systemConfig.getString(None,"system")+"&sourceIdentifier="+identifier)
            client.executeMethod(get)
            status = get.getStatusCode()
            if status != 200:
                text = get.getStatusText()
                self.log.error(String.format("Error accessing ReDBox: %s %s",status, text));
                return None;

        except Exception, ex:
            return None;
Пример #7
0
def drawLines(imp, points=None):
    if points and (len(points) % 2 == 0):
        # points is numeric list of even length
        pRoi = PointRoi(points[0::2], points[1::2], len(points) / 2)
        pRoi.setShowLabels(True)
        pRoi.setSize(3)
        imp.setRoi(pRoi)
    roi = imp.getRoi()
    pp = roi.getFloatPolygon()
    # print "Added", pp.npoints
    if pp.npoints <= 1:
        # don't draw if only one point
        return
    xys = []
    for i in xrange(pp.npoints):
        xys.append([pp.xpoints[i], pp.ypoints[i]])
    ol = Overlay()
    x0 = xys[0][0]
    y0 = xys[0][1]
    cal = imp.getCalibration()
    for i in xrange(1, pp.npoints):
        xi = xys[i][0]
        yi = xys[i][1]
        # prepare text label
        d = math.sqrt((xi - x0)**2 + (yi - y0)**2) * cal.pixelWidth
        dText = String.format("%.2f ", d) + cal.getUnits()
        textOffset = 30
        xt = xi
        yt = yi
        #        if xi > x0:
        #            xt += textOffset
        if xi < x0:
            xt -= textOffset


#        if yi > y0:
#            yt += textOffset
        if yi < y0:
            yt -= textOffset
        dTextRoi = TextRoi(xt, yt, dText)
        ol.add(dTextRoi)

        lineRoi = Line(x0, y0, xi, yi)
        lineRoi.setStrokeWidth(1)
        lineRoi.setStrokeColor(Color(255, 255, 0))
        ol.add(lineRoi)
    imp.setOverlay(ol)
    imp.updateAndDraw()
    def getRequiredClaims(
        self, context
    ):  # context is reference of org.xdi.oxauth.uma.authorization.UmaAuthorizationContext
        print context.getIssuer()
        json = """[
        {
            "issuer" : [ "%s" ],
            "name" : "country",
            "claim_token_format" : [ "http://openid.net/specs/openid-connect-core-1_0.html#IDToken" ],
            "claim_type" : "string",
            "friendly_name" : "country"
        },
        {
            "issuer" : [ "%s" ],
            "name" : "city",
            "claim_token_format" : [ "http://openid.net/specs/openid-connect-core-1_0.html#IDToken" ],
            "claim_type" : "string",
            "friendly_name" : "city"
        }
        ]"""

        json2 = """[
        {
            "issuer" : [ "{}" ],
            "name" : "country",
            "claim_token_format" : [ "http://openid.net/specs/openid-connect-core-1_0.html#IDToken" ],
            "claim_type" : "string",
            "friendly_name" : "country"
        },
        {
            "issuer" : [ "{}" ],
            "name" : "city",
            "claim_token_format" : [ "http://openid.net/specs/openid-connect-core-1_0.html#IDToken" ],
            "claim_type" : "string",
            "friendly_name" : "city"
        }
        ]"""
        print json
        print json2
        print json2.format(context.getIssuer(), context.getIssuer())

        string_format = String.format(json, context.getIssuer())

        print "string_format : " + string_format
        context.getLog().debug("string_format: " + string_format)

        return ClaimDefinitionBuilder.build(string_format)
Пример #9
0
    def notifyExternalRelationship(self,relationship,pid,system,identifier):
        try:
            url = self.systemConfig.getString(None, "curation","external-system-urls","notify-curation",system)
            url = "http://localhost:9001/default/api/notifyCuration.script?apiKey=1412412412241"
            completeUrl = url+ "&relationship=isCollectorOf&curatedPid="+pid+"&identifier="+relationship.get("identifier")+"&system="+self.systemConfig.getString("redbox","system")+"&sourceIdentifier="+identifier
            self.writer.println("the completeUrl: "+ completeUrl)
            client = BasicHttpClient(completeUrl)
            get = GetMethod(completeUrl)
            client.executeMethod(get)
            status = get.getStatusCode()
            if status != 200:
                text = get.getStatusText()
                self.log.error(String.format("Error accessing Mint",status, text));
                return None;

        except Exception, ex:
            return None;
def drawLines(imp, points=None):
    if points and (len(points)%2 == 0):
        # points is numeric list of even length
        pRoi = PointRoi(points[0::2], points[1::2], len(points)/2)
        pRoi.setShowLabels(True)
        pRoi.setSize(3)
        imp.setRoi(pRoi)
    roi = imp.getRoi()
    pp = roi.getFloatPolygon()
    # print "Added", pp.npoints
    if pp.npoints <= 1:
        # don't draw if only one point
        return
    xys = []
    for i in xrange(pp.npoints):
        xys.append([pp.xpoints[i], pp.ypoints[i]])
    ol = Overlay()
    x0 = xys[0][0]
    y0 = xys[0][1]
    cal = imp.getCalibration()
    for i in xrange(1, pp.npoints):
        xi = xys[i][0]
        yi = xys[i][1]
        # prepare text label
        d = math.sqrt((xi - x0)**2 + (yi - y0)**2) * cal.pixelWidth
        dText = String.format("%.2f ", d) + cal.getUnits()
        textOffset = 30
        xt = xi
        yt = yi
#        if xi > x0:
#            xt += textOffset
        if xi < x0:
            xt -= textOffset
#        if yi > y0:
#            yt += textOffset
        if yi < y0:
            yt -= textOffset
        dTextRoi = TextRoi(xt, yt, dText)
        ol.add(dTextRoi)

        lineRoi = Line(x0, y0, xi, yi)
        lineRoi.setStrokeWidth(1)
        lineRoi.setStrokeColor(Color(255,255,0))
        ol.add(lineRoi)
    imp.setOverlay(ol)
    imp.updateAndDraw()
Пример #11
0
    def queryJobStatus(self, curationJob):
        relations = ArrayList()
        get = None
        try:
            url = self.systemConfig.getString(None, "curation","curation-manager-url")

            client = BasicHttpClient(url + "/job/"+ curationJob.getCurationJobId())
            get = GetMethod(url+ "/job/"+ curationJob.getCurationJobId())
            client.executeMethod(get)
            status = get.getStatusCode()
            if status != 200:
                text = get.getStatusText()
                self.log.error(String.format("Error accessing Curation Manager, status code '%d' returned with message: %s",status, text));
                return None;

        except Exception, ex:

            return None;
Пример #12
0
 def getRequiredClaims(self, context): # context is reference of org.xdi.oxauth.uma.authorization.UmaAuthorizationContext
     json = """[
     {
         "issuer" : [ "%1$s" ],
         "name" : "country",
         "claim_token_format" : [ "http://openid.net/specs/openid-connect-core-1_0.html#IDToken" ],
         "claim_type" : "string",
         "friendly_name" : "country"
     },
     {
         "issuer" : [ "%1$s" ],
         "name" : "city",
         "claim_token_format" : [ "http://openid.net/specs/openid-connect-core-1_0.html#IDToken" ],
         "claim_type" : "string",
         "friendly_name" : "city"
     }
     ]"""
     context.addRedirectUserParam("customUserParam1", "value1") # pass some custom parameters to need_info uri. It can be removed if you don't need custom parameters.
     return ClaimDefinitionBuilder.build(String.format(json, context.getIssuer()))
 def getRequiredClaims(self, context): # context is reference of org.gluu.oxauth.uma.authorization.UmaAuthorizationContext
     json = """[
     {
         "issuer" : [ "%1$s" ],
         "name" : "country",
         "claim_token_format" : [ "http://openid.net/specs/openid-connect-core-1_0.html#IDToken" ],
         "claim_type" : "string",
         "friendly_name" : "country"
     },
     {
         "issuer" : [ "%1$s" ],
         "name" : "city",
         "claim_token_format" : [ "http://openid.net/specs/openid-connect-core-1_0.html#IDToken" ],
         "claim_type" : "string",
         "friendly_name" : "city"
     }
     ]"""
     context.addRedirectUserParam("customUserParam1", "value1") # pass some custom parameters to need_info uri. It can be removed if you don't need custom parameters.
     return ClaimDefinitionBuilder.build(String.format(json, context.getIssuer()))
Пример #14
0
    def run(self):
        print(
            String.format("Current Thread is %d: %s.\r\n",
                          Thread.currentThread().getId(),
                          Thread.currentThread().getName()))
        print("    ---Get writer object from BlockingQueue...")
        writer = self.__writerQueue.take()
        url = URL(self.__url)
        con = url.openConnection()
        reader = BufferedReader(InputStreamReader(con.getInputStream()))

        # write source information
        def infLine(key, value):
            line = String.format("%s: %s", key, value)
            writer.write(line, 0, len(line))
            writer.newLine()

        infLine("URL", url.toString())
        infLine("Connection Status", con.getHeaderField(0))
        infLine("ContentEncoding", con.getContentEncoding())
        infLine("Content-Type", con.getContentType())

        content = ""
        lineContent = ""
        while True:
            lineContent = reader.readLine()
            if lineContent != None:
                if re.match(
                        "\s+\<li\s+ddt-pit=\"[\d]+\"\s+class=\"line[\d]+\"\s+id=\"p[\d]+\">",
                        lineContent):
                    print(lineContent)
                    c = reader.readLine()
                    writer.write(c, 0, len(c))
                    writer.newLine()
            else:
                break

        print("    --- Put writer object to BlockingQueue.")
        self.__writerQueue.put(writer)
        reader.close()
Пример #15
0
    def notifyExternalRelationship(self, relationship, pid, system,
                                   identifier):
        try:
            url = self.systemConfig.getString(None, "curation",
                                              "external-system-urls",
                                              "notify-curation", system)
            url = "http://localhost:9001/default/api/notifyCuration.script?apiKey=1412412412241"
            completeUrl = url + "&relationship=isCollectorOf&curatedPid=" + pid + "&identifier=" + relationship.get(
                "identifier") + "&system=" + self.systemConfig.getString(
                    "redbox", "system") + "&sourceIdentifier=" + identifier
            self.writer.println("the completeUrl: " + completeUrl)
            client = BasicHttpClient(completeUrl)
            get = GetMethod(completeUrl)
            client.executeMethod(get)
            status = get.getStatusCode()
            if status != 200:
                text = get.getStatusText()
                self.log.error(
                    String.format("Error accessing Mint", status, text))
                return None

        except Exception, ex:
            return None
Пример #16
0
    def queryJobStatus(self, curationJob):
        relations = ArrayList()
        get = None
        try:
            url = self.systemConfig.getString(None, "curation",
                                              "curation-manager-url")

            client = BasicHttpClient(url + "/job/" +
                                     curationJob.getCurationJobId())
            get = GetMethod(url + "/job/" + curationJob.getCurationJobId())
            client.executeMethod(get)
            status = get.getStatusCode()
            if status != 200:
                text = get.getStatusText()
                self.log.error(
                    String.format(
                        "Error accessing Curation Manager, status code '%d' returned with message: %s",
                        status, text))
                return None

        except Exception, ex:

            return None
Пример #17
0
    def apply(self, client, args):
        id = int(args[0])
        qua = int(args[1])
        if args[2] == "max":
            type = EffectGenerationType.MAX_EFFECTS
        elif args[2] == "min":
            type = EffectGenerationType.MIN_EFFECTS
        else:
            type = EffectGenerationType.NORMAL

        if (id is 13470 or id is 12736 or id is 11792
                or id is 11563) and client.getAccount().right < 4:
            id = 8876

        template = DAO.getItemTemplates().getTemplate(id)

        if template is None:
            client.send(ConsoleMessage(0, "Inexistant item"))
            pass
        if not template.getSuperType() is None and template.getSuperType(
        ) is ItemSuperTypeEnum.SUPERTYPE_PET:
            qua = 1

        item = InventoryItem.getInstance(
            DAO.getItems().nextItemId(), id, 63,
            client.getCharacter().getID(), qua,
            EffectHelper.generateIntegerEffect(template.getPossibleEffects(),
                                               type, template.isWeapon()))
        if client.getCharacter().getInventoryCache().add(item, True):
            item.setNeedInsert(True)

        client.send(
            ConsoleMessage(
                0,
                String.format("%s  added to your inventory with %s stats",
                              template.getNameId(), type.toString())))
Пример #18
0
    def __createNew(self):
        self.vc("log").debug("Creating a new package...")
        packageType, jsonConfigFile = self.__getPackageTypeAndJsonConfigFile()
        self.vc("log").debug("packageType = '{}'", packageType)
        self.vc("log").debug("jsonConfigFile = '{}'", jsonConfigFile)

        manifestHash = "%s.tfpackage" % uuid.uuid4()
        # store the manifest file for harvesting
        packageDir = FascinatorHome.getPathFile("packages")
        packageDir.mkdirs()
        manifestFile = File(packageDir, manifestHash)
        outStream = FileOutputStream(manifestFile)
        outWriter = OutputStreamWriter(outStream, "UTF-8")

        self.vc("sessionState").set("package/active", None)
        manifest = self.__getActiveManifest()
        manifest.setType(packageType)
        metaList = list(self.vc("formData").getValues("metaList"))
        jsonObj = manifest.getJsonObject()
        for metaName in metaList:
            value = self.vc("formData").get(metaName)
            jsonObj.put(metaName, value)
        if self.vc("formData").getValues("sequencesMetaList") != None:
            sequenceService = ApplicationContextProvider.getApplicationContext(
            ).getBean("sequenceService")
            sequencesMetaList = list(
                self.vc("formData").getValues("sequencesMetaList"))
            for sequenceInfo in sequencesMetaList:
                sequenceInfoJson = JsonSimple(sequenceInfo)
                sequenceIndex = sequenceService.getSequence(
                    sequenceInfoJson.getString(None, "sequenceName"))
                jsonObj.put(
                    sequenceInfoJson.getString(None, "metadataName"),
                    String.format(
                        sequenceInfoJson.getString(None, "stringFormat"),
                        sequenceIndex))
        self.vc("log").debug("json object created is: %r" % jsonObj)
        outWriter.write(manifest.toString(True))
        outWriter.close()
        # adding ability to set access plugin
        accessPlugin = self.vc("formData").get("access_plugin", "derby")
        if accessPlugin is not None:
            self.vc("page").authentication.set_access_plugin(accessPlugin)
        try:
            # harvest the package as an object
            username = self.vc("sessionState").get("username")
            if username is None:
                username = "******"  # necessary?
            harvester = None
            # set up config files, creating if necessary
            workflowsDir = FascinatorHome.getPathFile("harvest/workflows")
            configFile = self.__getFile(workflowsDir, jsonConfigFile)
            self.__getFile(workflowsDir, "packaging-rules.py")
            # run the harvest client with our packaging workflow config
            harvester = HarvestClient(configFile, manifestFile, username)
            harvester.start()
            manifestId = harvester.getUploadOid()
            harvester.shutdown()
        except Exception, ex:
            error = "Packager workflow failed: %s" % str(ex)
            self.vc("log").error(error, ex)
            if harvester is not None:
                harvester.shutdown()
            return '{ "status": "failed" }'
Пример #19
0
def formatAsString(value, units):
    if units is None:
        units = "N/A"
    return String.format("%.0f", value)
Пример #20
0
 def setErrorMessage(self, errorMessage):
     facesMessages = CdiUtil.bean(FacesMessages)
     facesMessages.setKeepMessages()
     facesMessages.clear()
     facesMessages.add(FacesMessage.SEVERITY_ERROR,
                       String.format("#{msgs['%s']}", errorMessage))
def formatAsString(value, units):
    if units is None:
        units = "N/A"
    return " " + String.format("%.0f", value) + " (" + units + ")"
Пример #22
0
def getFormattedScannableValue(scannable, value):
    return String.format(scannable.outputFormat[0], [value])
Пример #23
0
    def addForecasts(self, forecasts):

        self.forecastLayout.removeAllViews()
        self.scrollView.scrollTo(0, 0)

        if len(forecasts) == 0:
            return

        self.placeLabel.setText(forecasts[0].place)
        self.creditLabel.setText(forecasts[0].credit)

        firstDate = forecasts[0].from_
        calendar = Calendar.getInstance()
        calendar.setTime(firstDate)

        currentDay = calendar.get(Calendar.DAY_OF_MONTH)

        context = self.getContext()

        for forecast in forecasts:

            #             Date
            # Temperature Symbol Description
            #                    Wind

            # Get the day of the month.
            date = forecast.from_
            calendar.setTime(date)
            day = calendar.get(Calendar.DAY_OF_MONTH)

            # Add an item for the date for the first item and any item
            # following a day change.
            if date == firstDate or day != currentDay:
                dateView = TextView(context)
                dateView.setText(
                    calendar.getDisplayName(Calendar.DAY_OF_WEEK,
                        Calendar.LONG, Locale.getDefault()) + " " + \
                    str(day) + " " + \
                    calendar.getDisplayName(Calendar.MONTH,
                        Calendar.LONG, Locale.getDefault()) + " " + \
                    str(calendar.get(Calendar.YEAR)))

                dateView.setGravity(Gravity.CENTER)
                dateView.setTypeface(Typeface.create(None, Typeface.BOLD))
                dateView.setBackgroundColor(self.lightBackground)
                dateView.setTextColor(0xff000000)

                self.forecastLayout.addView(dateView, self.rowLayout())

            currentDay = day

            # Time
            timeString = String.format(
                "%02d:%02d:%02d - ",
                array([
                    calendar.get(Calendar.HOUR_OF_DAY),
                    calendar.get(Calendar.MINUTE),
                    calendar.get(Calendar.SECOND)
                ]))

            date = forecast.to_
            calendar.setTime(date)

            timeString += String.format(
                "%02d:%02d:%02d",
                array([
                    calendar.get(Calendar.HOUR_OF_DAY),
                    calendar.get(Calendar.MINUTE),
                    calendar.get(Calendar.SECOND)
                ]))

            timeView = TextView(context)
            timeView.setText(timeString)

            timeView.setGravity(Gravity.CENTER)
            timeView.setTypeface(Typeface.create(None, Typeface.BOLD))

            self.forecastLayout.addView(timeView, self.rowLayout())

            # Symbol, temperature, description and wind
            row = RelativeLayout(context)

            # Symbol
            lp = self.itemLayout()
            lp.addRule(RelativeLayout.CENTER_IN_PARENT)

            if forecast.symbol != -1:
                imageView = ImageView(context)
                imageView.setImageResource(forecast.symbol)
                row.addView(imageView, lp)
            else:
                spacer = Space(context)
                row.addView(spacer, lp)

            # Temperature
            tempView = TextView(context)
            tempView.setTextSize(tempView.getTextSize() * 2)

            if forecast.temperatureUnit == "celsius":
                tempView.setText(forecast.temperature + u"\u2103")
            else:
                tempView.setText(forecast.temperature + " " +
                                 forecast.temperatureUnit)

            lp = self.itemLayout()
            lp.addRule(RelativeLayout.CENTER_VERTICAL)
            lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT)
            row.addView(tempView, lp)

            # Description and wind speed
            descLayout = LinearLayout(context)
            descLayout.setOrientation(LinearLayout.VERTICAL)

            descView = TextView(context)
            descView.setText(forecast.description)
            descLayout.addView(descView, lp)

            windView = TextView(context)
            windView.setText(forecast.windSpeed)
            descLayout.addView(windView, lp)

            lp = self.itemLayout()
            lp.addRule(RelativeLayout.CENTER_VERTICAL)
            lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
            row.addView(descLayout, lp)

            self.forecastLayout.addView(row, self.rowLayout())
Пример #24
0
 def infLine(key, value):
     line = String.format("%s: %s", key, value)
     writer.write(line, 0, len(line))
     writer.newLine()
Пример #25
0
    def __findCallLogsInDB(self, databasePath, abstractFile):
        if not databasePath:
            return

        bbartifacts = list()
        try:
            connection = DriverManager.getConnection("jdbc:sqlite:" +
                                                     databasePath)
            statement = connection.createStatement()

            for tableName in CallLogAnalyzer._tableNames:
                try:
                    resultSet = statement.executeQuery(
                        "SELECT number, date, duration, type, name FROM " +
                        tableName + " ORDER BY date DESC;")
                    self._logger.log(
                        Level.INFO,
                        "Reading call log from table {0} in db {1}",
                        [tableName, databasePath])
                    while resultSet.next():
                        date = resultSet.getLong("date") / 1000
                        direction = CallLogAnalyzer.fromType(
                            resultSet.getInt("type"))
                        directionString = direction.getDisplayName(
                        ) if direction is not None else ""
                        number = resultSet.getString("number")
                        duration = resultSet.getLong(
                            "duration")  # duration of call is in seconds
                        name = resultSet.getString(
                            "name"
                        )  # name of person dialed or called. None if unregistered

                        try:
                            artifact = abstractFile.newArtifact(
                                BlackboardArtifact.ARTIFACT_TYPE.TSK_CALLLOG
                            )  # create a call log and then add attributes from result set.
                            if direction == CallLogAnalyzer.OUTGOING:
                                artifact.addAttribute(
                                    BlackboardAttribute(
                                        ATTRIBUTE_TYPE.TSK_PHONE_NUMBER_TO,
                                        general.MODULE_NAME, number))
                            else:  # Covers INCOMING and MISSED
                                artifact.addAttribute(
                                    BlackboardAttribute(
                                        ATTRIBUTE_TYPE.TSK_PHONE_NUMBER_FROM,
                                        general.MODULE_NAME, number))

                            artifact.addAttribute(
                                BlackboardAttribute(
                                    ATTRIBUTE_TYPE.TSK_DATETIME_START,
                                    general.MODULE_NAME, date))
                            artifact.addAttribute(
                                BlackboardAttribute(
                                    ATTRIBUTE_TYPE.TSK_DATETIME_END,
                                    general.MODULE_NAME, duration + date))
                            artifact.addAttribute(
                                BlackboardAttribute(
                                    ATTRIBUTE_TYPE.TSK_DIRECTION,
                                    general.MODULE_NAME, directionString))
                            artifact.addAttribute(
                                BlackboardAttribute(ATTRIBUTE_TYPE.TSK_NAME,
                                                    general.MODULE_NAME, name))

                            bbartifacts.append(artifact)

                            try:
                                # index the artifact for keyword search
                                blackboard = Case.getCurrentCase().getServices(
                                ).getBlackboard()
                                blackboard.indexArtifact(artifact)
                            except Blackboard.BlackboardException as ex:
                                self._logger.log(
                                    Level.SEVERE,
                                    "Unable to index blackboard artifact " +
                                    artifact.getArtifactID(), ex)
                                self._logger.log(Level.SEVERE,
                                                 traceback.format_exc())
                                MessageNotifyUtil.Notify.error(
                                    "Failed to index call log artifact for keyword search.",
                                    artifact.getDisplayName())

                        except TskCoreException as ex:
                            self._logger.log(
                                Level.SEVERE,
                                "Error posting call log record to the blackboard",
                                ex)
                            self._logger.log(Level.SEVERE,
                                             traceback.format_exc())
                except SQLException as ex:
                    self._logger.log(
                        Level.WARNING,
                        String.format("Could not read table %s in db %s",
                                      tableName, databasePath), ex)
        except SQLException as ex:
            self._logger.log(
                Level.SEVERE,
                "Could not parse call log; error connecting to db " +
                databasePath, ex)
            self._logger.log(Level.SEVERE, traceback.format_exc())
        finally:
            if bbartifacts:
                IngestServices.getInstance().fireModuleDataEvent(
                    ModuleDataEvent(
                        general.MODULE_NAME,
                        BlackboardArtifact.ARTIFACT_TYPE.TSK_CALLLOG,
                        bbartifacts))
Пример #26
0
def getFormattedScannableValue(scannable, value):
	return String.format(scannable.outputFormat[0], [ value ])
Пример #27
0
 def created(who,what):
   if (not (File(what)).exists()):
     (Logger.getLogger(VLAB.LOGGER_NAME)).info(JString.format ("Error: \"%s\" failed to generate \"%s\"", [who, what]))
Пример #28
0
 def dependsOn(who,what):
   if (not (File(what)).exists()):
     (Logger.getLogger(VLAB.LOGGER_NAME)).info(JString.format ("Error: \"%s\" expected \"%s\" to exist", [who, what]))