def parse(self, query, field="", op="", version=None, parser=None, **attrs): """Return parsed lucene Query. :param query: query string :param field: default query field name, sequence of names, or boost mapping :param op: default query operator ('or', 'and') :param version: lucene Version :param parser: custom PythonQueryParser class :param attrs: additional attributes to set on the parser """ # parsers aren't thread-safe (nor slow), so create one each time cls = ( queryparser.classic.QueryParser if isinstance(field, basestring) else queryparser.classic.MultiFieldQueryParser ) args = field, self if isinstance(field, collections.Mapping): boosts = HashMap() for key in field: boosts.put(key, Float(field[key])) args = list(field), self, boosts parser = (parser or cls)(version or util.Version.LATEST, *args) if op: parser.defaultOperator = getattr(queryparser.classic.QueryParser.Operator, op.upper()) for name, value in attrs.items(): setattr(parser, name, value) if isinstance(parser, queryparser.classic.MultiFieldQueryParser): return parser.parse(parser, query) try: return parser.parse(query) finally: if isinstance(parser, PythonQueryParser): parser.finalize()
def test_hashmap_builtin_pymethods(self): x = HashMap() x['a'] = 1 x[(1, 2)] = 'xyz' self.assertEqual({tup for tup in x.iteritems()}, {('a', 1), ((1, 2), 'xyz')}) self.assertEqual(str(x), repr(x)) self.assertEqual(type(str(x)), type(repr(x)))
class ProcessDbUtils(discoverydbutils.DiscoveryDbUtils): # DELETESQL = 'delete from %s where hostid=\'%s\' and stamp < ' + str(System.currentTimeMillis() - PROCESS_EXPIRATION_PERIOD) DELETESQL = 'delete from %s where hostid=\'%s\' and stamp < %s' CONTEXT = 'processes' def __init__(self, Framework): discoverydbutils.DiscoveryDbUtils.__init__(self, Framework, ProcessDbUtils.CONTEXT) self.knownPortsConfigFile = Framework.getConfigFile(CollectorsParameters.KEY_COLLECTORS_SERVERDATA_PORTNUMBERTOPORTNAME) self.applicSignConfigFile = Framework.getConfigFile(CollectorsParameters.KEY_COLLECTORS_SERVERDATA_APPLICATIONSIGNATURE) self.pid2Process = HashMap() globalSettings = GeneralSettingsConfigFile.getInstance() self.PROCESS_EXPIRATION_PERIOD = globalSettings.getPropertyIntegerValue('processExpirationTime', 60) * 1000L def addProcess(self, hostId, name, process_pid, process_cmdline = None, process_path = None, process_parameters = None, process_owner = None, process_startuptime = None): if process_pid != 0: if process_path is None: if process_cmdline is not None: index = process_cmdline.lower().find(name.lower()) if index != -1: process_path = process_cmdline[:index] process = Process(hostId, name, process_pid, process_cmdline, process_path, process_parameters, process_owner, process_startuptime) self.addToBulk(process) if (process_pid > 0) and (process_cmdline is not None): self.pid2Process.put(str(process_pid),(process_cmdline)) def flushHostProcesses(self, hostId): self.executeUpdate(ProcessDbUtils.DELETESQL % ('Processes', str(hostId), str(System.currentTimeMillis() - self.PROCESS_EXPIRATION_PERIOD))) self.executeBulk(Process.PROCESSTYPE); def getProcessCmdMap(self): '-> map(str, str)' return self.pid2Process
def info(dspath): # get datastore shp = "file://%s" % os.path.abspath(dspath) params = HashMap() params.put("url", net.URL(shp)) dataStore = DataStoreFinder.getDataStore(params) typeName = dataStore.getTypeNames()[0] featureSource = dataStore.getFeatureSource(typeName) featureCollection = featureSource.getFeatures() featureType = featureSource.getSchema() # Print out feature source info (ie layer info) #'getBounds', 'getClass', 'getCount', 'getDataStore' print "Datastore : ", featureSource.getDataStore() print "Layer Name : ", typeName print "Number of features: ", featureCollection.count print "Bounding Box : ", featureSource.getBounds() # Print out feature attribute types for atype in featureType.getAttributeTypes(): print atype.getName(), atype.getType() return None f_iter = featureCollection.iterator() while f_iter.hasNext(): feat = f_iter.next() print "==============", feat.getID() for i in range(feat.getNumberOfAttributes()): print "\t %s " % feat.getAttribute(i) featureCollection.close(f_iter)
def discoverPlans(self,oshv,sqlServerId,dbs): logger.debug("going to get jobs and plans") if self.discoveryOptions and self.discoveryOptions.discoverSqlJob: jobById=self.getSqlJobs(oshv, sqlServerId) else: jobById=HashMap() rs = self.connection.getTable(self.plansQuery) plans = HashMap() while(rs.next()): name = rs.getString('plan_name') id = rs.getString('plan_id') osh = ObjectStateHolder('sqlservermaintenanceplan') osh.setAttribute(Queries.DATA_NAME,name) osh.setAttribute('planId',id) osh.setContainer(sqlServerId) oshv.add(osh) if self.discoveryOptions and self.discoveryOptions.discoverDbUser: owner = rs.getString('owner') # Some plans may not have an owner so we need to check if owner: user = ObjectStateHolder('dbuser') user.setAttribute(Queries.DATA_NAME,owner) user.setContainer(sqlServerId) oshv.add(user) oshv.add(modeling.createLinkOSH('owner',user,osh)) plans.put(name,osh) rs.close() logger.debug("got plans: ", plans.keySet().toString()) self.discoverPlanJobs(oshv,sqlServerId,plans,jobById) self.discoverPlanDbs(oshv,plans,dbs)
def getMappedAllAttributesUser(self, saml_response_attributes): user = User() # Set custom object classes if self.userObjectClasses != None: print "Saml. Get mapped all attributes user. User custom objectClasses to add persons: '%s'" % Util.array2ArrayList(self.userObjectClasses) user.setCustomObjectClasses(self.userObjectClasses) # Prepare map to do quick mapping attributeService = AttributeService.instance() ldapAttributes = attributeService.getAllAttributes() samlUriToAttributesMap = HashMap() for ldapAttribute in ldapAttributes: saml2Uri = ldapAttribute.getSaml2Uri() if (saml2Uri == None): saml2Uri = attributeService.getDefaultSaml2Uri(ldapAttribute.getName()) samlUriToAttributesMap.put(saml2Uri, ldapAttribute.getName()) customAttributes = ArrayList() for key in saml_response_attributes.keySet(): ldapAttributeName = samlUriToAttributesMap.get(key) if ldapAttributeName == None: print "Saml. Get mapped all attributes user. Skipping saml attribute: '%s'" % key continue if StringHelper.equalsIgnoreCase(ldapAttributeName, "uid"): continue attribute = CustomAttribute(ldapAttributeName) attribute.setValues(saml_response_attributes.get(key)) customAttributes.add(attribute) user.setCustomAttributes(customAttributes) return user
def getFacetDisplays(self): facetDisplays = self.__portal.getMap("portal/facet-displays") if facetDisplays is None or facetDisplays.isEmpty(): facetDisplays = HashMap() facetDisplays.put("list", "List menu") facetDisplays.put("tree", "Dynamic tree") return facetDisplays
def save_and_get_complex(): '''Test saving entities containing mapped collection properties''' entity1 = TestEntities.ComplexEntity() entity1.setId("complex1") strings = ArrayList() strings.add("one") strings.add("two") entity1.setStringList(strings) ints = HashSet() ints.add(1) ints.add(2) entity1.setIntSet(ints) extended = HashMap() extended.put("prop1", "one") extended.put("prop2", "two") entity1.setExtendedProps(extended) service = EntityService(TestEntities.ComplexEntity) service.save(entity1) entity2 = service.get("complex1") assertNotNull(entity2) assertEquals(entity2.getId(), entity1.getId()) assertTrue(entity2.getStringList().contains("one")) assertTrue(entity2.getStringList().contains("two")) assertTrue(entity2.getIntSet().contains(java.lang.Long(1))) assertTrue(entity2.getIntSet().contains(java.lang.Long(2))) assertNotNull(entity2.getExtendedProps()) assertEquals(entity2.getExtendedProps().get("prop1"), "one") assertEquals(entity2.getExtendedProps().get("prop2"), "two")
def __getJson(self): rvtMap = HashMap() try: oid = 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()
def getApplicationHierarchy(self): appsProps = [] params = HashMap() params.put('OBJECT_TYPE', 'FUGR') params.put('REFRESH', 'X') # function = self.__client.getFunction('RS_COMPONENT_VIEW') # function.getImportParameterList().setValue("FUGR", "OBJECT_TYPE"); # function.getImportParameterList().setValue("X", "REFRESH"); fields = ArrayList() fields.add('ID') fields.add('TYPE') fields.add('NAME') fields.add('PARENT') fields.add('TEXT') appsRS = self.__client.executeFunction('RS_COMPONENT_VIEW', params, 'NODETAB', fields) while appsRS.next(): prop = Properties() prop.setProperty('id', appsRS.getString("ID")) prop.setProperty('type', appsRS.getString("TYPE")) prop.setProperty('data_name', appsRS.getString("NAME")) prop.setProperty('parent', appsRS.getString("PARENT")) prop.setProperty('description', appsRS.getString("TEXT")) appsProps.append(prop) return appsProps;
def getCheckInValues( self, cd, content, oracle, metadataList ): checkInMap = {} # Manditory Metadata checkInMap["dDocName"]= cd.metadata["Target.dDocName"] checkInMap["dDocTitle"]= cd.metadata["Target.dDocTitle"] checkInMap["dDocType"]= cd.metadata["Target.dDocType"] checkInMap["dDocAuthor"]= cd.metadata["Target.dDocAuthor"] checkInMap["dSecurityGroup"]= cd.metadata["Target.dSecurityGroup"] checkInMap["dDocAccount"]= cd.metadata["Target.dDocAccount"] # Custom Metadata mdMap = HashMap() map(lambda x: mdMap.put(x,cd.metadata["Target.%s" % x]), metadataList) checkInMap["customDocMetadata"] = oracle.map2IdcPropList(mdMap) # File filename = cd.metadata["Target.Filename"] if cd.metadata["Identify Metadata.Content-Type"] == "application/xhtml+xml": fileContents = Base64.encodeString(content.contentData) else: fileContents = content.contentData checkInMap["primaryFile"] = oracle.content2IdcFile(filename,fileContents) checkInMap["alternateFile"] = None # Extras propMap = {} # ... add more? checkInMap["extraProps"] = oracle.map2IdcPropList(propMap) return checkInMap
def setBuddyVariables(self, user, varDict): hashMap = HashMap() for key, value in varDict.items(): hashMap.put(key, value) self._helper.setBuddyVariables( user, hashMap )
def get_recids_changes(message): """Retrieves the recids of the last changed documents""" last_recid = None table = 'bibrec' if message.getParam("table"): table = str(message.getParam("table")) if message.getParam("last_recid"): #last_recid = int(Integer.cast_(message.getParam("last_recid")).intValue()) last_recid = int(str(message.getParam("last_recid"))) mod_date = None if message.getParam("mod_date"): mod_date = str(message.getParam("mod_date")) max_records = 10000 if message.getParam('max_records'): max_records = int(Integer.cast_(message.getParam("max_records")).intValue()) if last_recid and last_recid == -1: mod_date = None (wid, results) = api_calls.dispatch("get_recids_changes", last_recid, max_recs=max_records, mod_date=mod_date, table=table) if results: data, last_recid, mod_date = results out = HashMap() #.of_(String, JArray_int) for k,v in data.items(): out.put(k, JArray_int(v)) message.setResults(out) message.setParam('mod_date', mod_date) message.setParam('last_recid', last_recid)
def __constructUserJson(self, username): """ There are users managed by internal auth manager with no attributes There are users managed by external auth manages e.g. shibboleth who have attributes These users username is not necessarily the same as there normal display name This function currently solves this issue by checking commonName attribute for shibboleth users """ username = username.strip() userJson = JsonObject() userJson.put("userName", username) parameters = HashMap() # print "Checking user info for %s" % username parameters.put("username", username) userObjectList = self.authUserDao.query("getUser", parameters) # print "Returned size = %d" % userObjectList.size() if userObjectList.size() > 0: userObject = userObjectList.get(0) #Check if this is a user with attributes? attrb = userObject.getAttributes().get("commonName") if attrb is None: # print "We cannot find so called commonName, use %s instead" % username userJson.put("realName", username) else: # print "We found so called commonName, use %s instead of %s" % (attrb.getValStr(), username) userJson.put("realName", attrb.getValStr().strip()) else: # This should not be reached self.log.warn("What is going on here? why ends up here?") userJson.put("realName", username) return userJson
def makeComponentGroups(client, appServerOSH, ip, OSHVResult, enterprise, siteOSH): mapGroupNameToOSH = HashMap() compgrpListing = client.executeCmd('list compgrps')#@@CMD_PERMISION siebel protocol execution cgTbl = siebel_common.makeTable(compgrpListing) # sample output # CG_NAME CG_ALIAS CG_DESC_TEXT CG_DISP_ENABLE_ST CG_NUM_COMP SV_NAME CA_RUN_STATE # --------------------------------------- ---------- -------------------------------------------------- ----------------- ----------- ------- ------------ # Assignment Management AsgnMgmt Assignment Management Components Enabled 2 sblapp2 Online # Communications Management CommMgmt Communications Management Components Enabled 7 sblapp2 Online # Content Center ContCtr Content Center Components Enabled 2 sblapp2 Online # Enterprise Application Integration EAI Enterprise Application Integration Components Enabled 10 sblapp2 Online # Field Service FieldSvc Field Service Components Enabled 13 sblapp2 Online # <... more> # n rows returned. cgcount = 0 for cgEntry in cgTbl: cgObj = cgEntry[0] logger.debug(' cgEntry[0]:', cgEntry[0]) cgDataRow = cgEntry[1] cgOSH = makeCompGrp(cgObj, cgDataRow, appServerOSH) cgcount += 1 # in older versions, the component contains cg name # in later versions, the component contains cg alias cgName = cgObj[0] cgAlias = cgObj[1] cgOSH.setContainer(appServerOSH) OSHVResult.add(cgOSH) mapGroupNameToOSH.put(cgName,cgOSH) mapGroupNameToOSH.put(cgAlias,cgOSH) getGroupComponents(client, mapGroupNameToOSH, ip, OSHVResult, enterprise, siteOSH) logger.debug('parsed ', str(cgcount), ' component groups')
class FacetList: def __init__(self, name, results): self.__facetMap = HashMap() self.__facetList = ArrayList() facets = results.getFacets() if facets is None: return facet = facets.get(name) if facet is None: return facetData = facet.values() for value in facetData.keySet(): count = facetData.get(value) facet = Facet(name, value, count) self.__facetMap.put(value, facet) slash = value.rfind("/") if slash == -1: self.__facetList.add(facet) else: parent = self.__getFacet(value[:slash]) if parent is not None: parent.addSubFacet(facet) def __getFacet(self, name): return self.__facetMap.get(name) def getJsonList(self): jsonList = ArrayList() for facets in self.__facetList: jsonList.add(facets.getJson()) return jsonList
def enhancePages( self, project, connector_url, cq_user, cq_password, page_query, page_queryLib ): # Validate Parameters if not self.validInputs(connector_url,cq_user,cq_password,"asset_drive","asset_filenameAttr","asset_pathAttr",page_query,page_queryLib,"ia_path","ia_cacheCols"): return # HTTP Connection Details client = HttpClient() base64EncodedCredentials = Base64.encodeString("%s:%s" % (cq_user,cq_password)) header = Header("Authorization", "Basic %s" % (base64EncodedCredentials)) # Cycle through contentdescriptors specified by scope query query = queryLibrarianService.findQueryByName(page_queryLib, page_query) params = HashMap() params.put('projectId',project.id) res = queryLibrarianService.executeQuery(query, params) # Get cd for r in res: cd = r[0] post = PostMethod(connector_url) post.addRequestHeader(header) get = GetMethod(connector_url) get.addRequestHeader(header) try: payload = cd.getContent()[0].getContentData().encode("utf-8") [loadStatus, failureReason] = self.sendPayload(client,get,post,payload,cd.url) cd.metadata["Load.Status"] = loadStatus cd.metadata["Load.Failure Reason"] = failureReason if loadStatus != "SUCCESS": logger.error("url: %s, reason: %s" % (cd.url, failureReason)) except: cd.metadata["Load.Status"] = "FAILURE" cd.metadata["Load.Failure Reason"] = "Null content" logger.error("url: %s, reason: %s" % (cd.url, failureReason))
def solveTurns(self, model): """ generated source for method solveTurns """ # Before we can do anything else, we need a topological ordering on our forms ordering = getTopologicalOrdering(model.getIndependentSentenceForms(), model.getDependencyGraph()) ordering.retainAll(self.formsControlledByFlow) # Let's add function info to the consideration... functionInfoMap = HashMap() for form in constantForms: functionInfoMap.put(form, FunctionInfoImpl.create(form, self.constantChecker)) # First we set the "true" values, then we get the forms controlled by the flow... # Use "init" values trueFlowSentences = HashSet() for form in constantForms: if form.__name__ == self.INIT: for initSentence in constantChecker.getTrueSentences(form): trueFlowSentences.add(trueSentence) # Go through ordering, adding to trueFlowSentences addSentenceForms(ordering, trueFlowSentences, model, functionInfoMap) self.sentencesTrueByTurn.add(trueFlowSentences) while True: # Now we use the "next" values from the previous turn trueFlowSentences = HashSet() for sentence in sentencesPreviouslyTrue: if sentence.__name__ == self.NEXT: trueFlowSentences.add(trueSentence) addSentenceForms(ordering, trueFlowSentences, model, functionInfoMap) # Test if this turn's flow is the same as an earlier one while i < len(self.sentencesTrueByTurn): if prevSet == trueFlowSentences: # Complete the loop self.turnAfterLast = i break i += 1 self.sentencesTrueByTurn.add(trueFlowSentences)
def getPublishersFromDistributor(self,oshv,distributor, distributorDatabaseName,sqlServerId): #check if i am a distributor first rs = self.connection.doCall('exec sp_helpdistpublisher') publishers = HashMap() sqlServers = HashMap() while(rs.next()): publisherName = rs.getString('name') publisher = ObjectStateHolder('sqlserverpublisher') sqlServer = self.createSqlServer(publisherName,oshv,sqlServerId) publisher.setContainer(sqlServer) publisher.setAttribute(Queries.DATA_NAME,publisherName) publishers.put(publisherName,publisher) sqlServers.put(publisherName,sqlServer) oshv.add(sqlServer) oshv.add(publisher) oshv.add(modeling.createLinkOSH('dblink',publisher,distributor)) #add the dblink between the distributor and the publisher rs.close() if(publishers.size() == 0): return #for each publisher get the published dbs workingDatabase = self.connection.getWorkingDatabase() self.connection.setWorkingDatabase(distributorDatabaseName) itr = publishers.keySet().iterator() while (itr.hasNext()): publisherName = itr.next() publisher = publishers.get(publisherName) sqlServer = sqlServers.get(publisherName) self.getPublications(publisherName,sqlServer,publisher,oshv,sqlServerId) self.connection.setWorkingDatabase(workingDatabase)
def getUduid(client): OPTION_UD_UNIQUE_ID = "UD_UNIQUE_ID" try: uduid = None try: clientOptions = client.getOptionsMap() uduid = clientOptions.get(OPTION_UD_UNIQUE_ID) logger.debug("Get uduid from client:", uduid) except: logger.debug("Can't get uduid from client") pass if not uduid: from java.util import UUID uduid = UUID.randomUUID() logger.debug("Generated uduid:", uduid) from java.util import HashMap options = HashMap() options.put(OPTION_UD_UNIQUE_ID, str(uduid)) client.setOptionsMap(options) clientOptions = client.getOptionsMap() #Get the value again to make sure the new value was set to client uduid = clientOptions.get(OPTION_UD_UNIQUE_ID) logger.debug("Final value of uduid:", uduid) return uduid except: return None
def run(core, actor, target, commandString): if actor.getCombatFlag() > 0: return cell = actor.getContainer() building = actor.getGrandparent() ghost = actor.getSlottedObject('ghost') if not ghost or not cell or not building or not core.housingService.getPermissions(actor, cell): return if ghost.getAmountOfVendors() >= actor.getSkillModBase('manage_vendor'): actor.sendSystemMessage('@player_structure:full_vendors', 0) return suiOptions = HashMap() suiOptions.put(Long(1), '@player_structure:terminal') suiOptions.put(Long(2), '@player_structure:droid') # TODO add creatures window = core.suiService.createListBox(ListBoxType.LIST_BOX_OK_CANCEL, '@player_structure:vendor_type_t', '@player_structure:vendor_type_d', suiOptions, actor, None, 5) returnList = Vector() returnList.add('List.lstList:SelectedRow') window.addHandler(0, '', Trigger.TRIGGER_OK, returnList, handleFirstWindow) core.suiService.openSUIWindow(window) return
class FacetList: def __init__(self, name, json): self.__facetMap = HashMap() self.__facetList = ArrayList() entries = json.getList("facet_counts/facet_fields/" + name) for i in range(0, len(entries), 2): value = entries[i] count = entries[i+1] if count > 0: facet = Facet(name, value, count) self.__facetMap.put(value, facet) slash = value.rfind("/") if slash == -1: self.__facetList.add(facet) else: parent = self.__getFacet(value[:slash]) if parent is not None: parent.addSubFacet(facet) def __getFacet(self, name): return self.__facetMap.get(name) def getJsonList(self): jsonList = ArrayList() for facets in self.__facetList: jsonList.add(facets.getJson()) return jsonList
def drainPool(cls): """ generated source for method drainPool """ cls.distinctPool.clear() cls.functionPool.clear() cls.notPool.clear() cls.orPool.clear() cls.propositionPool.clear() cls.relationPool.clear() cls.rulePool.clear() cls.variablePool.clear() with lock_for_object(cls.variableCases): cls.variableCases.clear() # When draining the pool between matches, we still need to preserve the keywords # since there are global references to them. For example, the Prover state machine # has a reference to the GdlConstant "true", and that reference must still point # to the authoritative GdlConstant "true" after the pool is drained and another # game has begun. As such, when draining the constant pool, these special keywords # are set aside and returned to the pool after all of the other constants (which # were game-specific) have been drained. keywordConstants = HashMap() for keyword in KEYWORDS: keywordConstants.put(keyword, GdlPool.getConstant(keyword)) with lock_for_object(cls.constantCases): cls.constantPool.clear() cls.constantCases.clear() for keywordEntry in keywordConstants.entrySet(): cls.constantCases.put(keywordEntry.getKey(), keywordEntry.getKey()) cls.constantPool.put(keywordEntry.getKey(), keywordEntry.getValue())
def __getUserInfo(self, username): """ Query HibernateUser to get a user information There are users managed by internal auth manager with no attributes other than password There are users managed by external auth managers e.g. shibboleth who have attributes Each user, at the time of writing: 20140904, each user has multiple identical attribute sets, so, only the first one is used We put all available attributes of a user in to return value """ username = username.strip() authUserDao = ApplicationContextProvider.getApplicationContext().getBean("hibernateAuthUserDao") parameters = HashMap() parameters.put("username", username) userObjectList = authUserDao.query("getUser", parameters) userJson = JsonObject() userJson.put("username", username) try: if userObjectList.size() > 0: # One hit will be enough to get user object userJson = self.__constructUserAttribs(userObjectList.get(0), self.ATTRIB_FILTER) else: # This should not be reached with external sourced users self.log.warn("Wrong username or internal user is queried") except Exception, e: self.log.error("%s: cannot construct user attribute JSON, detail = %s" % (self.__class__.__name__ , str(e)))
def get_doc_phrase_freq(self, phrase, field, slop, ordered): """ Returns collection frequency for a given phrase and field. :param phrase: str :param field: field name :param slop: number of terms in between :param ordered: If true, term occurrences should be ordered :return: dictionary {doc: freq, ...} """ # creates span near query span_near_query = self.get_span_query(phrase.split(" "), field, slop=slop, ordered=ordered) # extracts document frequency self.open_searcher() index_reader_context = self.searcher.getTopReaderContext() term_contexts = HashMap() terms = TreeSet() span_near_query.extractTerms(terms) for term in terms: term_contexts.put(term, TermContext.build(index_reader_context, term)) leaves = index_reader_context.leaves() doc_phrase_freq = {} # iterates over all atomic readers for atomic_reader_context in leaves: bits = atomic_reader_context.reader().getLiveDocs() spans = span_near_query.getSpans(atomic_reader_context, bits, term_contexts) while spans.next(): lucene_doc_id = spans.doc() doc_id = atomic_reader_context.reader().document(lucene_doc_id).get(self.FIELDNAME_ID) if doc_id not in doc_phrase_freq: doc_phrase_freq[doc_id] = 1 else: doc_phrase_freq[doc_id] += 1 return doc_phrase_freq
def __constructInfoJson(self, username): """ There are users managed by internal auth manager with no attributes There are users managed by external auth managers e.g. shibboleth who have attributes We put all available attributes of a user in to return value """ # print "Query username = %s" % username username = username.strip() authUserDao = ApplicationContextProvider.getApplicationContext().getBean("hibernateAuthUserDao") parameters = HashMap() parameters.put("username", username) userObjectList = authUserDao.query("getUser", parameters) # print "Returned object = %s" % str(userObjectList) # print "Returned size = %d" % userObjectList.size() userJson = JsonObject() try: if userObjectList.size() > 0: # One hit will be enough to get user object userObj = userObjectList.get(0) attrbs = userObj.getAttributes() for attrb in attrbs.keySet(): # print "Attribute %s = %s) % (attrb, attrbs.get(attrb).getValStr()) userJson.put(attrb, attrbs.get(attrb).getValStr()) else: # This should not be reached with external sourced users self.log.warn("Wrong username? Every user should have a record") userJson.put("userName", username) except Exception, e: self.log.error("%s: cannot construct user attribute JSON, detail = %s" % (self.__class__.__name__ , str(e))) userJson.put("userName", username)
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()
def updateLocalRecordRelations(self, jobItems): oidIdentifierMap = HashMap() for jobItem in jobItems: oidIdentifierMap.put(jobItem.get("oid"),jobItem.get("required_identifiers")[0].get("identifier")) for jobItem in jobItems: type = jobItem.get("type"); targetSystem = self.systemConfig.getString(None, "curation", "supported-types", type); if targetSystem == "redbox": oid = jobItem.get("oid") digitalObject = StorageUtils.getDigitalObject(self.services.getStorage(), oid) tfPackagePid = self.getPackageData(digitalObject) metadataJsonPayload = digitalObject.getPayload(tfPackagePid) metadataJsonInstream = metadataJsonPayload.open() metadataJson = JsonSimple(metadataJsonInstream) metadataJsonPayload.close() relationships = metadataJson.getArray("relationships") if relationships is not None: for relationship in relationships: system = relationship.get("system") if system != "redbox" or system != None: url = self.systemConfig.getString("can't find it", "curation","external-system-urls","get-oid-for-identifier",system) client = BasicHttpClient(url+ "&identifier="+relationship.get("identifier")) get = GetMethod(url+ "&identifier="+relationship.get("identifier")) client.executeMethod(get) if get.getStatusCode() == 200: response = JsonSimple(get.getResponseBodyAsString()) relationship.put("curatedPid",oidIdentifierMap.get(response.getString(None,"oid"))) relationship.put("isCurated",True) #Now update the relationship on Mint's side break istream = ByteArrayInputStream(String(metadataJson.toString(True)).getBytes()) StorageUtils.createOrUpdatePayload(digitalObject,tfPackagePid,istream)
class ProverCache(object): """ generated source for class ProverCache """ contents = Map() def __init__(self): """ generated source for method __init__ """ self.contents = HashMap() # # * NOTE: The given sentence must have been renamed with a VariableRenamer. # def contains(self, renamedSentence): """ generated source for method contains """ return self.contents.containsKey(renamedSentence) def get(self, sentence, varRenamedSentence): """ generated source for method get """ cacheContents = self.contents.get(varRenamedSentence) if cacheContents == None: return None results = HashSet() for answer in cacheContents: results.add(Unifier.unify(sentence, answer)) return ArrayList(results) def put(self, sentence, renamedSentence, answers): """ generated source for method put """ results = HashSet() for answer in answers: results.add(Substituter.substitute(sentence, answer)) self.contents.put(renamedSentence, results)
def rawoaasolve(agent, sparkgoal, sparkparams, sparkpattern=None): oaa = _oaa(agent) iclgoal = value_to_icl(sparkgoal) iclparams = value_to_icl(sparkparams) iclanswers = IclList() debug("calling oaaSolve on %s", iclgoal) functor = iclgoal.functor logInfo("rawoaasolve[%s]"%functor) result = oaa.oaaSolve(iclgoal, iclparams, iclanswers) logInfo("rawoaasolve complete[%s]"%functor) if result: debug("oaaSolve returned success: %s", iclanswers) if not iclanswers.isList(): raise LowError("The call to oaaSolve returned a non-IclList answer: %s"%iclanswers) if sparkpattern is None: ans = icl_to_value(iclanswers) else: bindings = HashMap() iclpattern = value_to_icl(sparkpattern) anslist = [] for iclans in iclanswers.iterator(): bindings.clear() if UNIFIER.matchTerms(iclans, iclgoal, bindings): anslist.append(icl_to_value(UNIFIER.deref(iclpattern, bindings))) else: raise LowError("The call to oaaSolve returned an answer that doesn't unify with the query:\nans=%s\query=%s"%(iclans, iclgoal)) ans = List(anslist) logInfo("rawoaasolve answers deconstructed[%s]"%functor) return ans else: debug("oaaSolve return failure: %s", iclanswers) logError("rawoaasolve return failure with answers [%s]"%iclanswers) raise OAAError("The call to oaaSolve [goal %s] failed and returned %s"\ %(functor, iclanswers))
def execute(self): self.userName = request.getAttribute("UserName") user = self.userService.getUserByLoginName(self.userName) if self.canVisitUser(user) == False: response.writer.println(u"用户 " + self.userName + u"不存在 ") return fc = FileCache() content = fc.getUserFileCacheContent(self.userName, "user_friendlinks.html", 30) if content != "": response.getWriter().write(content) fc = None return count = self.params.safeGetIntParam("count") if count == 0: count = 10 qry = FriendQuery( "frd.userId, frd.friendId, u.trueName, u.nickName, u.loginName, u.userIcon, u.qq" ) qry.userId = user.getUserId() friend_list = qry.query_map(count) templateProcessor = __spring__.getBean("templateProcessor") map = HashMap() map.put("friend_list", friend_list) map.put("UserSiteUrl", self.getUserSiteUrl()) content = templateProcessor.processTemplate( map, "/WEB-INF/user/default/user_friendlinks.ftl", "utf-8") fc.writeUserFileCacheContent(self.userName, "user_friendlinks.html", content) response.getWriter().write(content) fc = None
def testStudentsViewReports(self): """ Option deciding whether students can view the originality report. s_view_report / sviewreports 0 = not allowed 1 = allowed default is 0 """ # First Test that Students can view the report opts = HashMap() opts.put('s_view_report','1') tiiasnnid = "/unittests/studcanviewreport/"+str(uuid.uuid1()) tiisiteid = str(uuid.uuid1()) self.tiireview_serv.createAssignment(tiisiteid, tiiasnnid, opts) tiiresult = self.tiireview_serv.getAssignment(tiisiteid, tiiasnnid) self.assertEquals(str(tiiresult['object']['sviewreports']),str('1')) # Test that Students cannot view the report opts.put('s_view_report','0') tiiasnnid = "/unittests/studcannotviewreport/"+str(uuid.uuid1()) self.tiireview_serv.createAssignment(tiisiteid, tiiasnnid, opts) tiiresult = self.tiireview_serv.getAssignment(tiisiteid, tiiasnnid) self.assertEquals(str(tiiresult['object']['sviewreports']),str('0'))
def execute(self): self.userName = request.getAttribute("loginName") userService = __jitar__.userService user = userService.getUserByLoginName(self.userName) if user == None: response.writer.println(u"不能加载该用户的信息") return if self.canVisitUser(user) == False: response.writer.println(u"用户 %s 无法访问." % self.userName) return fc = FileCache() content = fc.getUserFileCacheContent(self.userName, "user_placard.html", 30) if content != "": response.getWriter().write(content) fc = None return qry = PlacardQuery("pld.title, pld.createDate, pld.content") qry.objType = 1 qry.objId = user.getUserId() placard_list = qry.query_map(1) templateProcessor = __spring__.getBean("templateProcessor") map = HashMap() map.put("user", user) map.put("placard_list", placard_list) content = templateProcessor.processTemplate( map, "/WEB-INF/user/default/user_placard.ftl", "utf-8") fc.writeUserFileCacheContent(self.userName, "user_placard.html", content) response.getWriter().write(content) fc = None
def rawoaasolve(agent, sparkgoal, sparkparams, sparkpattern=None): oaa = _oaa(agent) iclgoal = value_to_icl(sparkgoal) iclparams = value_to_icl(sparkparams) iclanswers = IclList() debug("calling oaaSolve on %s", iclgoal) functor = iclgoal.functor logInfo("rawoaasolve[%s]" % functor) result = oaa.oaaSolve(iclgoal, iclparams, iclanswers) logInfo("rawoaasolve complete[%s]" % functor) if result: debug("oaaSolve returned success: %s", iclanswers) if not iclanswers.isList(): raise LowError( "The call to oaaSolve returned a non-IclList answer: %s" % iclanswers) if sparkpattern is None: ans = icl_to_value(iclanswers) else: bindings = HashMap() iclpattern = value_to_icl(sparkpattern) anslist = [] for iclans in iclanswers.iterator(): bindings.clear() if UNIFIER.matchTerms(iclans, iclgoal, bindings): anslist.append( icl_to_value(UNIFIER.deref(iclpattern, bindings))) else: raise LowError( "The call to oaaSolve returned an answer that doesn't unify with the query:\nans=%s\query=%s" % (iclans, iclgoal)) ans = List(anslist) logInfo("rawoaasolve answers deconstructed[%s]" % functor) return ans else: debug("oaaSolve return failure: %s", iclanswers) logError("rawoaasolve return failure with answers [%s]" % iclanswers) raise OAAError("The call to oaaSolve [goal %s] failed and returned %s"\ %(functor, iclanswers))
def __init__(self, index_dir, search_fields=['canonical_url', 'title', 'meta', 'content'], unique_field='uq_id_str', boost=dict(canonical_url=4.0, title=8.0, meta=2.0, content=1.0), date_format='%Y-%m-%dT%H:%M:%S'): """Constructor of Searcher. Parameters ---------- index_dir : string The location of lucene index. search_fields : list A list of field names indicating fields to search on. unique_field : string The field name, on which the duplication should avoid. boost : dict This dict control the weight when computing score. date_format : string Convert the string into datetime. Should consistent with the index part. """ self.index_dir = index_dir self.search_fields = search_fields self.sort_by_recent = Sort( SortField('date_published', SortField.Type.STRING, True)) self.store = FSDirectory.open(File(index_dir)) self.reader = DirectoryReader.open(self.store) self.isearcher = IndexSearcher(self.reader) self.analyzer = StandardAnalyzer() self.dup_filter = DuplicateFilter(unique_field) self.boost_map = HashMap() for k, v in boost.iteritems(): self.boost_map.put(k, Float(v)) self.mul_parser = MultiFieldQueryParser(search_fields, self.analyzer, self.boost_map) self.date_format = date_format
def execute(self): self.userName = request.getAttribute("UserName") userService = __jitar__.userService user = userService.getUserByLoginName(self.userName) if user == None: response.getWriter().write(u"无法加载当前用户对象,") return fc = FileCache() # 14400 为10 天 content = fc.getUserFileCacheContent(self.userName, "user_profile.html", 14400) if content != "": response.getWriter().write(content) fc = None return templateProcessor = __spring__.getBean("templateProcessor") map = HashMap() map.put("user", user) map.put("UserSiteUrl", self.getUserSiteUrl()) content = templateProcessor.processTemplate( map, "/WEB-INF/user/default/user_profile.ftl", "utf-8") fc.writeUserFileCacheContent(self.userName, "user_profile.html", content) response.getWriter().write(content) fc = None
def _loader_dict(self, cmd={}): self.loader_map = dict() for bucket in self.cluster.buckets: for scope in bucket.scopes.keys(): for collection in bucket.scopes[scope].collections.keys(): if collection == "_default" and scope == "_default": continue ws = WorkLoadSettings( cmd.get("keyPrefix", self.key), cmd.get("keySize", self.key_size), cmd.get("docSize", self.doc_size), cmd.get("cr", self.create_perc), cmd.get("rd", self.read_perc), cmd.get("up", self.update_perc), cmd.get("dl", self.delete_perc), cmd.get("ex", self.expiry_perc), cmd.get("workers", self.process_concurrency), cmd.get("ops", self.ops_rate), cmd.get("loadType", None), cmd.get("keyType", None), cmd.get("valueType", None), cmd.get("validate", False), cmd.get("gtm", False), cmd.get("deleted", False), cmd.get("mutated", 0)) hm = HashMap() hm.putAll({ DRConstants.create_s: self.create_start, DRConstants.create_e: self.create_end, DRConstants.update_s: self.update_start, DRConstants.update_e: self.update_end, DRConstants.expiry_s: self.expire_start, DRConstants.expiry_e: self.expire_end, DRConstants.delete_s: self.delete_start, DRConstants.delete_e: self.delete_end, DRConstants.read_s: self.read_start, DRConstants.read_e: self.read_end }) dr = DocRange(hm) ws.dr = dr dg = DocumentGenerator(ws, self.key_type, self.val_type) self.loader_map.update( {bucket.name + scope + collection: dg})
def prepareForStep(self, configurationAttributes, requestParameters, step): if step == 1: print "CAS2. Prepare for step 1" requestParameterService = CdiUtil.bean(RequestParameterService) httpService = CdiUtil.bean(HttpService) facesContext = CdiUtil.bean(FacesContext) request = facesContext.getExternalContext().getRequest() parametersMap = HashMap() parametersMap.put( "service", httpService.constructServerUrl(request) + "/postlogin.htm") if self.cas_renew_opt: parametersMap.put("renew", "true") cas_service_request_uri = requestParameterService.parametersAsString( parametersMap) cas_service_request_uri = self.cas_host + "/login?" + cas_service_request_uri if self.cas_extra_opts != None: cas_service_request_uri = cas_service_request_uri + "&" + self.cas_extra_opts print "CAS2. Prepare for step 1. cas_service_request_uri: " + cas_service_request_uri facesService = CdiUtil.bean(FacesService) facesService.redirectToExternalURL(cas_service_request_uri) return True elif step == 2: print "CAS2. Prepare for step 2" return True else: return False
def start_pr_release(repo_full_name, pr_number, pr_title, comment): tag = 'pull_request_merger' pr_templates = templateApi.getTemplates(tag) if not pr_templates: raise Exception('Could not find any templates by tag [pull_request_merger]. ' 'Did the xlr-development-workflow-plugin initializer run?') else: if len(pr_templates) > 1: logger.warn("Found more than one template with tag '%s', using the first one" % tag) template_id = pr_templates[0].id params = StartRelease() params.setReleaseTitle('Merge PR #%s: %s' % (pr_number, pr_title)) variables = HashMap() variables.put('${pull_request_number}', '%s' % pr_number) variables.put('${pull_request_title}', '%s' % pr_title) variables.put('${repository_full_name}', '%s' % repo_full_name) variables.put('${pull_request_comment}', '%s' % comment) params.setReleaseVariables(variables) started_release = templateApi.start(template_id, params) response.entity = started_release logger.info("Started release %s to merge pull request %s" % (started_release.getId(), pr_number))
def genernate_group_content(self, webpart): cache_key = "unit" + str(self.unit.unitId) + "_" + str( webpart.getUnitWebpartId()) content = cache.get(cache_key) if content != None: request.setAttribute(cache_key, content) return qry = UnitGroupQuery("ug.groupName,ug.groupTitle") qry.unitId = self.unit.unitId unitGroupList = qry.query_map(10) map = HashMap() map.put("unit", self.unit) map.put("webpart", webpart) map.put("UnitRootUrl", self.unitRootUrl) map.put("unitGroupList", unitGroupList) content = self.templateProcessor.processTemplate( map, "/WEB-INF/unitspage/" + self.templateName + "/unit_group.ftl", "utf-8") request.setAttribute(cache_key, content) cache.put(cache_key, content)
def getMintLabels(self, urlName, key, suffix): mapIds = HashMap() valList = self.getList(key) self.log.debug(valList.toString()) ids = "" for eKey in valList.keySet(): entry = valList.get(eKey) if len(ids) > 0: ids = "%s," % ids ids = "%s%s" % (ids, entry.get(suffix)) if ids == "": return None else: labels = ArrayList() mapIds.put("id", ids) labelsMint = MintLookupHelper.get(self.systemConfig, urlName, mapIds) self.log.debug(labelsMint.getJsonArray().toString()) for label in labelsMint.getJsonArray(): labelJson = JsonSimple(label) labels.add(labelJson.getString("", "label")) return labels
def nx_update_custom_attr(self): ''' Check _categoryName on node, if it is not set to the current value (or missing) update it ''' required_attrs = { '_categoryName': self.category, 'disableUnreachableAlarms': str(int(self.category in (self.WORKSTATION, self.PORTABLE, self.PRINTER))), 'disableInterfaceAlarms': str(int(self.category in (self.WORKSTATION, self.PORTABLE, self.PRINTER))) } for attr in required_attrs: ca = self.node.customAttributes.get(attr, None) if ca and ca.value == required_attrs[attr]: del required_attrs[attr] if required_attrs: md = NXCObjectModificationData(self.node.getObjectId()) attr_map = HashMap(self.node.getCustomAttributes()) flags = CustomAttribute.INHERITABLE for attr in required_attrs: attr_map.put(attr, CustomAttribute(str(required_attrs[attr]), flags, 0)) md.setCustomAttributes(attr_map) self.session.modifyObject(md)
def __init__(self, Framework, OSHVResult, credentialId=None): ''' Default initializator that uses ip_address and ip_domain from the passed Framework. @types: Framework, osh vector, str -> None''' self.Framework = Framework self.OSHVResult = OSHVResult self.ip_address = Framework.getDestinationAttribute('ip_address') self.ip_domain = Framework.getDestinationAttribute('ip_domain') self.credentialID = credentialId self.connected = 0 self.errorMsg = [] #used to not to report several server oshs with same name (to prevent multiple updates on port) self.discoveredServers = HashMap()
def setupForcedPhotometryVisits(): vars = HashMap() f = open(SCRIPT_LOCATION + "/" + VISIT_FILE) for line in f.readlines(): dir, visit, f = line.split() vars.put("FILTER", f) vars.put("VISIT", visit) pipeline.createSubstream("processForcedPhotometry", int(visit), vars)
def getJavaMap(d=None, **kwargs): m = HashMap() if d is not None: for key, val in d.iteritems(): m.put(key, val) for key, val in kwargs.iteritems(): m.put(key, val) return m
def __init__(self, parent=None, type_=None): # stays null for most scopes (mem opt) # all are non-null except global table # link to the closest non-class scope, for lifting functions out # .... if not hasattr(self, 'scopeType'): self.scopeType = None self.supers = List() self.globalNames = Set() self.type_ = None self.path = "" self.parent = parent self.setScopeType(type_) self.forwarding = None self.table = Map() if isinstance(parent, Scope) and type_ is None: s = parent # case of creating a new scope from an existing one if s.table is not None: self.table = HashMap() self.table.update(s.table) self.parent = s.parent self.setScopeType(s.scopeType) self.forwarding = s.forwarding self.supers = s.supers self.globalNames = s.globalNames self.type_ = s.type_ self.path = s.path elif parent is not None: self.parent = parent self.setScopeType(type_) if type_ == self.ScopeType.CLASS: self.forwarding = (None if parent is None else parent.getForwarding()) else: self.forwarding = self
def checkLock(Framework): probe = CollectorsParameters.getValue(CollectorsParameters.KEY_PROBE_MGR_IP) if (probe is None) or (len(str(probe)) == 0): logger.debug('Probe manager ip is not specified in the DiscoveryProbe.properties file, using probe ID') probe = CollectorsParameters.getValue(CollectorsParameters.KEY_COLLECTORS_PROBE_NAME) jobType = INVENTORY_JOB_TYPE jobId = Framework.getDiscoveryJobId() lockTime = System.currentTimeMillis() lockExpiration = System.currentTimeMillis() + LOCK_AGE_PERIOD_MILLISECONDS lock = Lock(probe, jobType, jobId, lockTime, lockExpiration) logger.debug('Checking remote lock with current lock:', str(lock.getLockInfo())) triggerid = Framework.getTriggerCIData('id') logger.debug('Checking lock for probe ', probe, ' and jobid ', jobId, ' and triggerid ', triggerid) client = Framework.getConnectedClient() options = getClientOptionsMap(client) lockOption = options.get(ScannerNodeLock) if (lockOption is None) or (len(lockOption.strip()) == 0): logger.debug('Lock on scanner node for probe "' + lock.probe + '" and job "' + lock.jobId + '" is not exists') return 0 remoteLock = extractLock(lockOption) logger.debug('Found remote lock:', str(remoteLock.getLockInfo())) if remoteLock.isLockExpired(): logger.debug('Lock on remote node is already expired, renewing lock on the node') options = HashMap() options.put(ScannerNodeLock, lock.getLockInfo()) client.setOptionsMap(options) elif not lock.isSameLock(remoteLock): logger.debug( 'Lock on remote node is owned by another probe/job (' + remoteLock.probe + '/' + remoteLock.jobId + ')') if remoteLock.jobType == CALLHOME_JOB_TYPE: return ScannerNodeLockedByCallHome return 0 return 1
def convertListToHashMap(J2EEProperySetList): # print "Properties for %s" % (obj) map = HashMap() if (len(J2EEProperySetList) == 0):return map propsetList = [] # print "Propset= %s" % (propset) try: for psItem in J2EEProperySetList: # print "psItem %s" % (psItem) propname = AdminConfigShowAttribute(psItem, "name") propvalue = AdminConfigShowAttribute(psItem, "value") # print "--------------" # print "propname " + str(propname) # print "propvalue " + str(propvalue) # print "--------------" map.put(propname, propvalue) # end for except: print "KO" type, value, traceback = sys.exc_info() print "ERROR: %s (%s)" % (str(value), type) return map return map
def readModules(): mapCategoryToAppComponent = HashMap() try: builder = SAXBuilder(0) separator = CollectorsParameters.FILE_SEPARATOR fileLocation = CollectorsParameters.BASE_PROBE_MGR_DIR + separator + 'discoveryResources' + separator + 'sap-application-components.xml' doc = builder.build(FileReader(File(fileLocation))) root = doc.getRootElement() categories = root.getChildren('category') if categories != None: itCat = categories.iterator() while itCat.hasNext(): categoryElem = itCat.next() category = categoryElem.getAttributeValue('name') applicationComponents = categoryElem.getChildren( 'application-component') itComp = applicationComponents.iterator() while itComp.hasNext(): component = itComp.next().getAttributeValue('name') mapCategoryToAppComponent.put(component, category) except: logger.errorException('Failed to read modules') return mapCategoryToAppComponent
def createNewAuthenticatedSession(self, context, customParameters={}): sessionIdService = CdiUtil.bean(SessionIdService) user = context.getUser() client = CdiUtil.bean(Identity).getSessionClient().getClient() # Add mandatory session parameters sessionAttributes = HashMap() sessionAttributes.put(Constants.AUTHENTICATED_USER, user.getUserId()) sessionAttributes.put(AuthorizeRequestParam.CLIENT_ID, client.getClientId()) sessionAttributes.put(AuthorizeRequestParam.PROMPT, "") # Add custom session parameters for key, value in customParameters.iteritems(): if StringHelper.isNotEmpty(value): sessionAttributes.put(key, value) # Generate authenticated session sessionId = sessionIdService.generateAuthenticatedSessionId(context.getHttpRequest(), user.getDn(), sessionAttributes) print "ROPC script. Generated session id. DN: '%s'" % sessionId.getDn() return sessionId
def getScripts(self): from java.util import HashMap from com.raytheon.viz.gfe.smarttool.script import SmartToolMetadata scriptList = HashMap() for script in self.scripts: try: (element, screenList, hideTool, docString, varDict) = self.__getToolInfo(script) name = str(script) if screenList is not None: screenList = JUtil.pyValToJavaObj(screenList) hideTool = bool(hideTool) docString = str(docString) metadata = SmartToolMetadata(name, element, screenList, hideTool, docString, varDict) scriptList.put(name, metadata) except: self.log.exception("Unable to load metadata for smart tool " + script) return scriptList
def getMappedAllAttributesUser(self, saml_response_attributes): user = User() # Set custom object classes if self.userObjectClasses != None: print "Asimba. Get mapped all attributes user. User custom objectClasses to add persons: '%s'" % Util.array2ArrayList( self.userObjectClasses) user.setCustomObjectClasses(self.userObjectClasses) # Prepare map to do quick mapping attributeService = CdiUtil.bean(AttributeService) ldapAttributes = attributeService.getAllAttributes() samlUriToAttributesMap = HashMap() for ldapAttribute in ldapAttributes: saml2Uri = ldapAttribute.getSaml2Uri() if saml2Uri == None: saml2Uri = attributeService.getDefaultSaml2Uri( ldapAttribute.getName()) samlUriToAttributesMap.put(saml2Uri, ldapAttribute.getName()) customAttributes = ArrayList() for key in saml_response_attributes.keySet(): ldapAttributeName = samlUriToAttributesMap.get(key) if ldapAttributeName == None: print "Asimba. Get mapped all attributes user. Skipping saml attribute: '%s'" % key continue if StringHelper.equalsIgnoreCase(ldapAttributeName, "uid"): continue attribute = CustomAttribute(ldapAttributeName) attribute.setValues(saml_response_attributes.get(key)) customAttributes.add(attribute) user.setCustomAttributes(customAttributes) return user
def execute(self): channelId = self.params.safeGetIntParam("channelId") if channelId == 0: self.addActionError(u"您所访问的页面不存在!") return ActionResult.ACCESS_ERROR self.channel = self.channelPageService.getChannel(channelId) if self.channel == None: self.addActionError(u"无法加载指定的页面!") return ActionResult.ACCESS_ERROR map = HashMap() map.put("channel", self.channel) head_nav = "user" # 输出页头 headerContent = self.GenerateContentFromTemplateString( self.channel.headerTemplate, head_nav) footerContent = self.GenerateContentFromTemplateString( self.channel.footerTemplate, head_nav) # 输出主体部分: qry = ChannelUserQuery( " cu.userId, user.loginName, user.userTags, user.articleCount, user.userIcon, user.blogName,user.trueName, user.createDate, user.visitCount, user.myArticleCount, user.otherArticleCount, user.resourceCount, user.commentCount,user.userScore " ) qry.channelId = self.channel.channelId pager = self.createPager() pager.totalRows = qry.count() user_list = qry.query_map(pager) map.put("user_list", user_list) map.put("pager", pager) if self.channel.skin == None: skin = "template1" elif self.channel.skin == "": skin = "template1" else: skin = self.channel.skin mainContent = self.templateProcessor.processTemplate( map, "/WEB-INF/channel/" + skin + "/channel_user.ftl", "utf-8") out = response.getWriter() if headerContent == "" and footerContent == "" and mainContent == "": out.println(u"该频道没有指定模板,无法显示页面内容。") return out.println(headerContent) out.println(mainContent) out.println(footerContent)
def sort_deployeds(): deployeds_per_key = HashMap() for _delta in deltas.deltas: deployed = _delta.deployedOrPrevious if deployed.type == "rh.TomcatWARModule": key = "%s___%s" % (deployed.appName, deployed.container.name) if deployeds_per_key.containsKey(key): deployeds_per_key.get(key).add(deployed) else: result = HashSet() result.add(deployed) deployeds_per_key.put(key, result) return deployeds_per_key
def processCis(allObjectChildren, client, ciDictionary, objectMappings, action, updateStatus): iter = allObjectChildren.iterator() while iter.hasNext(): objectElement = iter.next() table = objectElement.getAttributeValue('name') id = objectElement.getAttributeValue('id') mode = objectElement.getAttributeValue('mode') operation = objectElement.getAttributeValue('operation') attributesMap = HashMap() fieldChildren = objectElement.getChildren('field') if fieldChildren is not None: iter2 = fieldChildren.iterator() while iter2.hasNext(): fieldElement = iter2.next() fieldName = fieldElement.getAttributeValue('name') fieldValue = fieldElement.getText() attributesMap.put(fieldName,fieldValue) isKey = fieldElement.getAttributeValue('key') objId = CmdbObjectID.Factory.restoreObjectID(id) newId = objId.getPropertyValue(ID_KEY) externalId = None if (newId is None): #if this is CMDB id cmdbId = objId.getPropertyValue('internal_id') newId = str(client.getNextCounter()) attributesMap.put('ID', newId) propArray = [TypesFactory.createProperty(ID_KEY, attributesMap.get(ID_KEY))] className = objId.getType() externalId = ExternalIdFactory.createExternalCiId(className, propArray) objectMappings.put(cmdbId, externalId) else: logger.info('objId is external and objId.getPropertyValue is ', newId) externalId = ExternalIdUtil.restoreExternalCiId(objId.toString()) attributesMap.put('ID', newId) ciDictionary.put(id, newId) if (action == ADD): client.executeInsert(table, attributesMap, updateStatus, externalId) elif (action == UPDATE): client.executeUpdate(table, attributesMap, newId, updateStatus, externalId) elif (action == DELETE): client.executeDelete(table, attributesMap, newId, updateStatus, externalId)
def genernate_vote_content(self, webpart): cache_key = "unit" + str(self.unit.unitId) + "_" + str( webpart.getUnitWebpartId()) content = cache.get(cache_key) if content != None: request.setAttribute(cache_key, content) return map = HashMap() map.put("unit", self.unit) map.put("webpart", webpart) map.put("UnitRootUrl", self.unitRootUrl) content = self.templateProcessor.processTemplate( map, "/WEB-INF/unitspage/" + self.templateName + "/unit_vote.ftl", "utf-8") request.setAttribute(cache_key, content) cache.put(cache_key, content)
def genernate_picnews_content(self, webpart): cache_key = "unit" + str(self.unit.unitId) + "_" + str( webpart.getUnitWebpartId()) content = cache.get(cache_key) if content != None: request.setAttribute(cache_key, content) return map = HashMap() qry = UnitNewsNoticeQuery( """ un.unitNewsId, un.title, un.picture, un.createDate""") qry.unitId = self.unit.unitId qry.itemType = 0 pic_news = qry.query_map(6) map.put("pic_news", pic_news) map.put("unit", self.unit) map.put("webpart", webpart) map.put("UnitRootUrl", self.unitRootUrl) content = self.templateProcessor.processTemplate( map, "/WEB-INF/unitspage/" + self.templateName + "/pic_news.ftl", "utf-8") request.setAttribute(cache_key, content) cache.put(cache_key, content)
def genernate_video_content(self, webpart): cache_key = "unit" + str(self.unit.unitId) + "_" + str( webpart.getUnitWebpartId()) content = cache.get(cache_key) if content != None: request.setAttribute(cache_key, content) return map = HashMap() qry = VideoQuery( """ v.videoId, v.title, v.createDate, v.href, v.flvHref, v.userId, u.loginName, u.nickName, v.summary,v.flvThumbNailHref """ ) qry.orderType = VideoQuery.ORDER_TYPE_VIDEOID_DESC qry.unitId = self.unit.unitId new_video_list = qry.query_map(4) map.put("new_video_list", new_video_list) map.put("unit", self.unit) map.put("webpart", webpart) map.put("UnitRootUrl", self.unitRootUrl) content = self.templateProcessor.processTemplate( map, "/WEB-INF/unitspage/" + self.templateName + "/video.ftl", "utf-8") request.setAttribute(cache_key, content) cache.put(cache_key, content)
def create_subject_nav(self): subjectService = __spring__.getBean("subjectService") qry = Command(" SELECT DISTINCT metaGrade.gradeId FROM Subject Order By metaGrade.gradeId ASC") mGradeId = qry.open() MetaGrade = ArrayList() metaSubject = ArrayList() for grade in mGradeId: mGrade = subjectService.getGrade(int(grade)) MetaGrade.add(mGrade) subj = subjectService.getSubjectByGradeId(int(grade)) m = ArrayList() if subj != None: for sj in range(0, subj.size()): m.add(subj[sj].metaSubject) metaSubject.add({"gradeName" : mGrade.gradeName, "gradeId" : grade, "metaSubject" : m }) map = HashMap() map.put("metaGrade", MetaGrade) map.put("meta_Grade", MetaGrade) map.put("SubjectNav", metaSubject) map.put("SiteUrl", request.getContextPath() + "/") templateProcessor = __spring__.getBean("templateProcessor") str = templateProcessor.processTemplate(map, "/WEB-INF/ftl/site_subject_nav.ftl", "utf-8") rootPath = JitarRequestContext.getRequestContext().getServletContext().getRealPath("/") fileIndex = rootPath + "html" + File.separator + "subject_nav.html" try: file = File(fileIndex) fw = OutputStreamWriter(FileOutputStream(file), "utf-8") #fw = FileWriter(file, False) fw.flush() fw.write(str) fw.close() finally: file = None fw = None request.setAttribute("errorMessage", u"生成学科导航缓存文件完毕!")