Exemple #1
0
 def __getJson(self):
     rvtMap = JsonObject()
     try:
         oid = self.vc("formData").get("oid")
         object = Services.storage.getObject(oid)
         payload = object.getPayload("imsmanifest.xml")
         try:
             from xml.etree import ElementTree
             xmlStr = IOUtils.toString(payload.open(), "UTF-8")
             payload.close()
             xml = ElementTree.XML(xmlStr.encode("UTF-8"))
             ns = xml.tag[:xml.tag.find("}")+1]
             resources = {}
             for res in xml.findall(ns+"resources/"+ns+"resource"):
                 resources[res.attrib.get("identifier")] = res.attrib.get("href")
             organizations = xml.find(ns+"organizations")
             defaultName = organizations.attrib.get("default")
             organizations = organizations.findall(ns+"organization")
             organizations = [o for o in organizations if o.attrib.get("identifier")==defaultName]
             organization = organizations[0]
             title = organization.find(ns+"title").text
             rvtMap.put("title", title)
             items = organization.findall(ns+"item")
             rvtMap.put("toc", self.__getJsonItems(ns, items, resources))
         except Exception, e:
              data["error"] = "Error - %s" % str(e)
              print data["error"]
         object.close()
Exemple #2
0
 def __getRvtManifest(self, manifest):
     rvtMap = HashMap()
     rvtMap.put("title", manifest.getTitle())
     rvtMap.put("toc", self.__getRvtNodes(manifest.getTopNodes()))
     json = JsonObject(rvtMap)
     #print json.toString()
     return json.toString()
Exemple #3
0
 def __getPackageTypes(self):
     object = self.sysConfig.getObject(["portal", "packageTypes"])
     packageTypes = JsonSimple.toJavaMap(object)
     if packageTypes.isEmpty():
         defaultPackage = JsonObject()
         defaultPackage.put("jsonconfig", "packaging-config.json")
         packageTypes.put("default", JsonSimple(defaultPackage))
     return packageTypes
Exemple #4
0
    def __activate__(self, context):
        self.sysConfig = JsonSimpleConfig()
        self.velocityContext = context
        self.__meta = {}
        formData = self.vc("formData")

        self.isAjax = self.vc("formData").get("ajax") != None
        if self.isAjax:
            ok = JsonObject()
            ok.put("ok", "OK")
            self.json = ok.toString()
        else:
            self.json = ""

        self.__selectedPackageType = formData.get("packageType", "default")
        #print "formData=%s" % self.vc("formData")
        #print "selectedPackageType='%s'" % self.__selectedPackageType
        self.__meta["packageType"] = formData.get("packageType", "default")
        self.__meta["description"] = formData.get("description", "")
Exemple #5
0
 def getJson(self, state = "open"):
     title = "%s (%s)" % (self.getName(), self.getCount())
     json = JsonSimple()
     jsonObj = json.getJsonObject()
     attributes = JsonObject()
     attributes.put("id", self.getId())
     attributes.put("fq", self.getFacetQuery())
     attributes.put("title", title)
     jsonObj.put("data", title)
     jsonObj.put("attributes", attributes)
     hasSubFacets = not self.getSubFacets().isEmpty()
     if hasSubFacets:
         jsonObj.put("state", state)
         subFacetList = ArrayList()
         for subFacet in self.getSubFacets():
             subFacetList.add(subFacet.getJson("closed"))
         children = JSONArray()
         children.addAll(subFacetList)
         jsonObj.put("children", children)
     return json
Exemple #6
0
    def process(self):
        print " * settings.py: formData=%s" % self.vc("formData")

        result = "{}"
        portalManager = Services.getPortalManager()
        portal = portalManager.get(self.vc("portalId"))
        func = self.vc("formData").get("func")

        if func == "view-update":
            portal.setDescription(self.vc("formData").get("view-description"))
            portal.setQuery(self.vc("formData").get("view-query"))
            portal.setSearchQuery(self.vc("formData").get("view-search-query"))
            portal.setRecordsPerPage(int(self.vc("formData").get("view-records-per-page")))
            portal.setFacetCount(int(self.vc("formData").get("view-facet-count")))
            portal.setFacetDisplay(int(self.vc("formData").get("view-facet-display")))
            portal.setFacetSort(self.vc("formData").get("view-facet-sort") is not None)
            portalManager.save(portal)

        elif func == "general-update":
            config = JsonSimpleConfig()
            email = StringUtils.trimToEmpty(self.vc("formData").get("general-email"))
            systemEmail = StringUtils.trimToEmpty(config.getString(None, ["email"]))
            if systemEmail != email:
                obj = config.writableSystemConfig()
                obj.put("email", self.vc("formData").get("general-email"))
                obj.put("configured", "true")
                config.storeSystemConfig()
                # mark restart
                Services.getHouseKeepingManager().requestUrgentRestart()
            else:
                print " * settings.py: email not updated: did not change"
                self.throw_error("Email address is the same! No change saved.")

        elif func == "facets-update":
            portal.getObject(["portal"]).remove("facet-fields")
            fields = self.vc("formData").getValues("field")
            labels = self.vc("formData").getValues("label")
            displays = self.vc("formData").getValues("display")
            deletes = self.vc("formData").getValues("delete")
            for i in range(0, len(fields)):
                field = fields[i]
                if deletes[i] == "false":
                    node = portal.writeObject(["portal", "facet-fields", field])
                    node.put("label", labels[i])
                    node.put("display", displays[i])
            portalManager.save(portal)

        elif func == "sort-update":
            portal.getObject(["portal"]).remove("sort-fields")
            default = self.vc("formData").get("default")
            if default:
                portal.setSortFieldDefault(default)
            order = self.vc("formData").get("order")
            if order:
                portal.setSortFieldDefaultOrder(order)
            fields = self.vc("formData").getValues("field")
            labels = self.vc("formData").getValues("label")
            deletes = self.vc("formData").getValues("delete")
            for i in range(0, len(fields)):
                field = fields[i]
                if deletes[i] == "false":
                    node = portal.writeObject(["portal", "sort-fields"])
                    node.put(field, labels[i])
            portalManager.save(portal)

        elif func == "watcher-update":
            configFile = self.getWatcherFile()
            if configFile is not None:
                json = JsonSimpleConfig(configFile)
                pathIds = self.vc("formData").get("pathIds").split(",")
                actives = self.vc("formData").getValues("watcher-active")
                if actives is None:
                    actives = []
                deletes = self.vc("formData").getValues("watcher-delete")
                if deletes is None:
                    deletes = []
                for pathId in pathIds:
                    if pathId not in deletes:
                        path = self.vc("formData").get("%s-path" % pathId)
                        stopped = str(pathId not in actives).lower()
                        watchDir = json.writeObject(["watcher", "watchDirs", path])
                        watchDir.put("ignoreFileFilter", self.vc("formData").get("%s-file" % pathId))
                        watchDir.put("ignoreDirectories", self.vc("formData").get("%s-dir" % pathId))
                        watchDir.put("stopped", stopped)
                        json.writeArray(["watcher", "watchDirs", path, "cxtTags"])
                writer = FileWriter(configFile)
                writer.write(json.toString(True))
                writer.close()
            else:
                result = "The Watcher is not installed properly."

        elif func == "restore-default-config":
            # backup the file
            JsonSimpleConfig.backupSystemFile()
            # delete the file
            JsonSimpleConfig.getSystemFile().delete()
            # restore default
            JsonSimpleConfig.getSystemFile()
            # mark restart
            Services.getHouseKeepingManager().requestUrgentRestart()

        elif func == "housekeeping-update":
            config = JsonSimpleConfig()
            freq = StringUtils.trimToEmpty(self.vc("formData").get("housekeeping-timeout"))
            systemFreq = StringUtils.trimToEmpty(config.getString(None, ["portal", "houseKeeping", "config", "frequency"]))
            result = "House Keeper refreshed"
            if systemFreq != freq:
                # Get writeable access to underlying system
                sysConfig = JsonSimple(config.writableSystemConfig())
                # Modify the house keeping node
                hkConfig = sysConfig.writeObject(["portal", "houseKeeping", "config"])
                hkConfig.put("frequency", freq)
                # Write the underlying config back to disk
                config.storeSystemConfig()
                result = "Frequency updated, refreshing House Keeper"
            # Refresh the HouseKeeper
            message = JsonObject()
            message.put("type", "refresh")
            Services.getHouseKeepingManager().sendMessage(message.toString())

        self.writer.println(result)
        self.writer.close()
Exemple #7
0
 def __activate__(self, context):
     response = context["response"]
     writer = response.getPrintWriter("text/plain; charset=UTF-8")
     auth = context["page"].authentication
     result = JsonObject()
     result.put("status", "error")
     result.put("message", "An unknown error has occurred")
     if auth.is_logged_in() and auth.is_admin():
         services = context["Services"]
         formData = context["formData"]
         func = formData.get("func")
         oid = formData.get("oid")
         portalId = formData.get("portalId")
         portalManager = services.portalManager
         if func == "reharvest":
             if oid:
                 print "Reharvesting object '%s'" % oid
                 portalManager.reharvest(oid)
                 result.put("status", "ok")
                 result.put("message", "Object '%s' queued for reharvest")
             elif portalId:
                 print " Reharvesting view '%s'" % portalId
                 # TODO security filter
                 # TODO this should loop through the whole portal,
                 #      not just the first page of results
                 portal = portalManager.get(portalId)
                 req = SearchRequest(portal.query)
                 req.setParam("fq", 'item_type:"object"')
                 out = ByteArrayOutputStream();
                 services.indexer.search(req, out)
                 json = SolrResult(ByteArrayInputStream(out.toByteArray()))
                 objectIds = json.getFieldList("id")
                 if not objectIds.isEmpty():
                     portalManager.reharvest(objectIds)
                 result.put("status", "ok")
                 result.put("message", "Objects in '%s' queued for reharvest" % portalId)
             else:
                 response.setStatus(500)
                 result.put("message", "No object or view specified for reharvest")
         elif func == "reindex":
             if oid:
                 print "Reindexing object '%s'" % oid
                 services.indexer.index(oid)
                 services.indexer.commit()
                 result.put("status", "ok")
                 result.put("message", "Object '%s' queued for reindex" % portalId)
             else:
                 response.setStatus(500)
                 result.put("message", "No object specified to reindex")
         else:
             response.setStatus(500)
             result.put("message", "Unknown action '%s'" % func)
     else:
         response.setStatus(500)
         result.put("message", "Only administrative users can access this API")
     writer.println(result.toString())
     writer.close()
Exemple #8
0
    def __activate__(self, context):
        response = context["response"]
        json = JsonObject()
        auth = context["page"].authentication
        if auth.is_logged_in():
            formData = context["formData"]
            oid = formData.get("oid")
            if oid:
                # TODO check security on object
                json.put("oid", oid)
                try:
                    metaNode = JsonObject()
                    json.put("meta", metaNode)

                    object = context["Services"].storage.getObject(oid)
                    metadata = object.getMetadata()

                    for key in metadata.keySet():
                        metaNode.put(key, metadata.get(key))
                except StorageException:
                    response.setStatus(500)
                    json.put("error", "Object '%s' not found" % oid)
            else:
                response.setStatus(500)
                json.put("error", "An object identifier is required")
        else:
            response.setStatus(500)
            json.put("error", "Only registered users can access this API")
        
        writer = response.getPrintWriter("text/plain; charset=UTF-8")
        writer.println(json.toString())
        writer.close()