def register_service(service, interface_names, properties=None): """ This function registers the specified service object with the specified properties under the specified class names into the Framework. Args: service (java.lang.Object): the service to register interface_names (list): a list of class names properties (dict): a dict of properties for the service Returns: ServiceRegistration: a ServiceRegistration object used to update or unregister the service """ if properties: from java.util import Hashtable properties_hashmap = Hashtable() for key, value in properties.iteritems(): properties_hashmap.put(key, value) properties = properties_hashmap registered_service = BUNDLE_CONTEXT.registerService( interface_names, service, properties) for name in interface_names: REGISTERED_SERVICES[name] = (service, registered_service) #LOG.debug("Registered service: {}".format(service)) #LOG.debug("REGISTERED_SERVICES: {}".format(REGISTERED_SERVICES)) return registered_service
def __createJMXConnection(self): "create JMX connection" self.__jmxConnection = None self.__jmxConnector = None try: jmxServiceUrl = JMXServiceURL(self.__jmxUrl) env = Hashtable() cred = array([self.__jmxUser, self.__jmxPassword], String) env.put("jmx.remote.credentials", cred) logger.info("Connecting to Oracle Coherence MBean Server:" + ` jmxServiceUrl `) self.__jmxConnector = JMXConnectorFactory.connect( jmxServiceUrl, env) self.__jmxConnection = self.__jmxConnector.getMBeanServerConnection( ) logger.info( "Successfully connected to Oracle Coherence MBean Server:" + ` jmxServiceUrl `) except: type, value, traceback = sys.exc_info() logger.finer("JMX Connection error:" + ` value `) self.__jmxConnection = None try: if self.__jmxConnector: self.__jmxConnector.close() self.__jmxConnector = None except: type, value, traceback = sys.exc_info() logger.finer("JMX Connector close error:" + ` value `)
def copy(self): """ Return Surface that is a copy of this surface. """ if not self._super_surface: img_properties = Hashtable() keys = self.getPropertyNames() if keys != None: for key in keys: img_properties.put(key, self.getProperty(key)) surface = Surface( self.getColorModel(), self.getData(), self.isAlphaPremultiplied(), img_properties ) surface._colorkey = self._colorkey else: surface = Surface((self.width, self.height), BufferedImage.TYPE_INT_ARGB) g2d = surface.createGraphics() g2d.drawImage(self, 0, 0, None) g2d.dispose() surface._colorkey = self._colorkey return surface
def hashtable(*key_values): """ :param key_values: 2-tuples of (key, value) :return: initialized Hashtable """ ht = Hashtable() for k, v in key_values: ht.put(k, v) return ht
def test_return_proxy(self): "Jython proxies properly return back from Java code" class FooVector(Vector): bar = 99 ht = Hashtable() fv = FooVector() ht.put("a", fv) self.assertTrue(fv is ht.get("a"))
def test_return_proxy(self): "Jython proxies properly return back from Java code" class FooVector(Vector): bar = 99 ht = Hashtable() fv = FooVector() ht.put("a", fv) self.failUnless(fv is ht.get("a"))
def lookup(self, ejbName): properties = Hashtable(); properties.put(FACTORY_INITIAL_KEY, FACTORY_INITIAL_VALUE); properties.put(FACTORY_URLPKGS_KEY, FACTORY_URLPKGS_VALUE); properties.put(PROVIDER_URL_KEY, PROVIDER_URL_VALUE); mylookup = None try: context = InitialContext(properties); mylookup = context.lookup(ejbName) except NoInitialContextException, err: raise Exception("Error with EJB connection[localhost:1099]\n" + str(err))
def lookup(ejbName): properties = Hashtable(); properties.put(lookup_properties.FACTORY_INITIAL_KEY, lookup_properties.FACTORY_INITIAL_VALUE); properties.put(lookup_properties.FACTORY_URLPKGS_KEY, lookup_properties.FACTORY_URLPKGS_VALUE); properties.put(lookup_properties.PROVIDER_URL_KEY, lookup_properties.PROVIDER_URL_VALUE); context = InitialContext(properties); mylookup = None try: mylookup = context.lookup(ejbName) except CommunicationException, err: raise Exception("Error with EJB connection[" + settings.SERVIDOR + ":1099]\n" + str(err))
def __init__(self, debugger): self.lastValue = None self.debugger = debugger MAX_SPEED = debugger.MAX_SPEED self.slider = swing.JSlider(swing.JSlider.HORIZONTAL, 0, MAX_SPEED, self.debugger.speed, stateChanged=self.stateChanged) self.last_speed = self.debugger.speed labels = Hashtable() labels.put(0, swing.JLabel('slow')) labels.put(MAX_SPEED, swing.JLabel('fast')) self.slider.labelTable = labels self.slider.paintLabels = 1 self.addButton = swing.JButton(swing.ImageIcon('images/plus.jpg'), actionPerformed=self.actionPerformed, toolTipText='add Variable', preferredSize=BUTTON_SIZE) self.deleteButton = swing.JButton(swing.ImageIcon('images/minus.jpg'), actionPerformed=self.actionPerformed, toolTipText='remove Variable', preferredSize=BUTTON_SIZE) self.stepButton = swing.JButton(swing.ImageIcon('images/boot.jpg'), actionPerformed=self.actionPerformed, toolTipText='step', preferredSize=BUTTON_SIZE) self.pauseIcon = swing.ImageIcon('images/pause.jpg') self.runIcon = swing.ImageIcon('images/run.jpg') self.runButton = swing.JButton(self.runIcon, actionPerformed=self.actionPerformed, toolTipText='run', preferredSize=BUTTON_SIZE) self.fullspeedButton = swing.JButton( swing.ImageIcon('images/fullspeed.jpg'), actionPerformed=self.actionPerformed, toolTipText='full speed', preferredSize=BUTTON_SIZE) self.stopButton = swing.JButton(swing.ImageIcon('images/stop.jpg'), actionPerformed=self.actionPerformed, toolTipText='stop', preferredSize=BUTTON_SIZE) self.setLayout(swing.BoxLayout(self, swing.BoxLayout.X_AXIS)) self.add(self.slider) self.add(self.addButton) self.add(self.deleteButton) #self.add(self.stepButton) # These two lines commented out by Brian O because of removed Pause functionality -- 23 June 2008 #self.add(self.runButton) self.add(self.fullspeedButton) self.add(self.stopButton) self.initialButtonState()
def __init__(self, debugger): self.lastValue = None self.debugger = debugger MAX_SPEED = debugger.MAX_SPEED self.slider = swing.JSlider(swing.JSlider.HORIZONTAL, 0, MAX_SPEED, self.debugger.speed, stateChanged=self.stateChanged) self.last_speed = self.debugger.speed labels = Hashtable() labels.put(0, swing.JLabel('slow')) labels.put(MAX_SPEED, swing.JLabel('fast')) self.slider.labelTable = labels self.slider.paintLabels = 1 self.addButton = swing.JButton(swing.ImageIcon('images/plus.jpg'), actionPerformed=self.actionPerformed, toolTipText='add Variable', preferredSize=BUTTON_SIZE) self.deleteButton = swing.JButton(swing.ImageIcon('images/minus.jpg'), actionPerformed=self.actionPerformed, toolTipText='remove Variable', preferredSize=BUTTON_SIZE) self.stepButton = swing.JButton(swing.ImageIcon('images/boot.jpg'), actionPerformed=self.actionPerformed, toolTipText='step', preferredSize=BUTTON_SIZE) self.pauseIcon = swing.ImageIcon('images/pause.jpg') self.runIcon = swing.ImageIcon('images/run.jpg') self.runButton = swing.JButton(self.runIcon, actionPerformed=self.actionPerformed, toolTipText='run', preferredSize=BUTTON_SIZE) self.fullspeedButton = swing.JButton(swing.ImageIcon('images/fullspeed.jpg'), actionPerformed=self.actionPerformed, toolTipText='full speed', preferredSize=BUTTON_SIZE) self.stopButton = swing.JButton(swing.ImageIcon('images/stop.jpg'), actionPerformed=self.actionPerformed, toolTipText='stop', preferredSize=BUTTON_SIZE) self.setLayout(swing.BoxLayout(self, swing.BoxLayout.X_AXIS)) self.add(self.slider) self.add(self.addButton) self.add(self.deleteButton) #self.add(self.stepButton) # These two lines commented out by Brian O because of removed Pause functionality -- 23 June 2008 #self.add(self.runButton) self.add(self.fullspeedButton) self.add(self.stopButton) self.initialButtonState()
def getdata(): defaultResultText = "Decoding Failed" qread = QRCodeReader() ip = IJ.getProcessor() myimg = ip.getBufferedImage() source = BufferedImageLuminanceSource(myimg) bitmap = BinaryBitmap(HybridBinarizer(source)) resultText = defaultResultText try : hints = Hashtable() hints.put(DecodeHintType.TRY_HARDER, True) result = qread.decode(bitmap, hints) resultText = result.getText() except NotFoundException, ex: print ex
def simple_bind_s(self, bind_user, bind_cred): self.user = bind_user self.cred = bind_cred env = Hashtable() env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory") env.put(Context.PROVIDER_URL, self.url) env.put(Context.SECURITY_AUTHENTICATION, "simple") env.put(Context.SECURITY_PRINCIPAL, self.user) env.put(Context.SECURITY_CREDENTIALS, self.cred) try: self.ctx = InitialDirContext(env) except NamingException, e: #e.printStackTrace() raise LDAPError(e)
def __init__(self, *arg): """ Return Surface that is subclassed from java.awt.image.BufferedImage. Alternative arguments: * Size (w,h) of surface, optional second argument of flags (SRCALPHA) * Bufferedimage to convert to Surface Module initialization places pyj2d.Surface in module's namespace. """ try: width, height = arg[0] try: if arg[1] & (BufferedImage.TYPE_INT_ARGB | Const.SRCALPHA): BufferedImage.__init__(self, width, height, BufferedImage.TYPE_INT_ARGB) else: BufferedImage.__init__(self, width, height, BufferedImage.TYPE_INT_RGB) except IndexError: BufferedImage.__init__(self, width, height, BufferedImage.TYPE_INT_ARGB) graphics2D = self.createGraphics() graphics2D.setColor(Color(0,0,0)) graphics2D.fillRect(0, 0, width, height) graphics2D.dispose() except TypeError: try: cm = arg[0].getColorModel() raster = arg[0].getRaster() isRasterPremultiplied = arg[0].isAlphaPremultiplied() properties = Hashtable() keys = arg[0].getPropertyNames() if keys != None: for key in keys: properties.put(key, arg[0].getProperty(key)) except AttributeError: cm, raster, isRasterPremultiplied, properties = arg BufferedImage.__init__(self, cm, raster, isRasterPremultiplied, properties) self._display = None #display surface self._super_surface = None self._offset = (0,0) self._colorkey = None self._nonimplemented_methods()
def fetch_ldap_group(self, file): """ fetch group mapping from group ldap server :param file: output file name """ self.logger.info("Fetching ldap groups") settings = Hashtable() settings.put(Context.INITIAL_CONTEXT_FACTORY, self.args[Constant.LDAP_GROUP_CONTEXT_FACTORY_KEY]) settings.put(Context.PROVIDER_URL, self.args[Constant.LDAP_GROUP_CONTEXT_PROVIDER_URL_KEY]) settings.put(Context.SECURITY_PRINCIPAL, self.args[Constant.LDAP_GROUP_CONTEXT_SECURITY_PRINCIPAL_KEY]) settings.put(Context.SECURITY_CREDENTIALS, self.args[Constant.LDAP_GROUP_CONTEXT_SECURITY_CREDENTIALS_KEY]) ctx = InitialDirContext(settings) search_target = "(objectClass=posixGroup)" return_attributes_standard = ['group_id', 'member_ids'] return_attributes_actual = json.loads(self.args[Constant.LDAP_GROUP_SEARCH_RETURN_ATTRS_KEY]) return_attributes_map = dict(zip(return_attributes_standard, return_attributes_actual)) ctls = SearchControls() ctls.setReturningAttributes(return_attributes_actual) ctls.setSearchScope(SearchControls.SUBTREE_SCOPE) ldap_records = [] org_units = json.loads(self.args[Constant.LDAP_GROUP_SEARCH_DOMAINS_KEY]) for search_unit in org_units: results = ctx.search(search_unit, search_target, ctls) for r in results: person_attributes = r.getAttributes() group = person_attributes.get(return_attributes_map['group_id']).get(0) group = re.sub(r"\r|\n", '', group).strip().encode('utf8') # skip special group that contains all group users if group == 'users': continue members = person_attributes.get(return_attributes_map['member_ids']) if members: self.group_map[group] = members sort_id = 0 for member in members.getAll(): member = re.sub(r"\r|\n", '', member).strip().encode('utf8') ldap_group_tuple = [self.group_app_id] ldap_group_tuple.append(group) ldap_group_tuple.append(sort_id) if member in self.ldap_user: ldap_group_tuple.append(self.app_id) else: ldap_group_tuple.append(self.group_app_id) ldap_group_tuple.append(member) ldap_group_tuple.append(self.wh_exec_id) ldap_records.append(ldap_group_tuple) sort_id += 1 else: pass self.logger.info("%d records found in group accounts" % (len(self.group_map))) csv_writer = csv.writer(open(file, "w"), delimiter='\x1a', quoting=csv.QUOTE_MINIMAL, lineterminator="\n") csv_writer.writerows(ldap_records)
def fetch_ldap_group(self, file): """ fetch group mapping from group ldap server :param file: output file name """ settings = Hashtable() settings.put(Context.INITIAL_CONTEXT_FACTORY, self.args[Constant.LDAP_GROUP_CONTEXT_FACTORY_KEY]) settings.put(Context.PROVIDER_URL, self.args[Constant.LDAP_GROUP_CONTEXT_PROVIDER_URL_KEY]) settings.put(Context.SECURITY_PRINCIPAL, self.args[Constant.LDAP_GROUP_CONTEXT_SECURITY_PRINCIPAL_KEY]) settings.put(Context.SECURITY_CREDENTIALS, self.args[Constant.LDAP_GROUP_CONTEXT_SECURITY_CREDENTIALS_KEY]) ctx = InitialDirContext(settings) search_target = "(objectClass=posixGroup)" return_attributes_standard = ['group_id', 'member_ids'] return_attributes_actual = json.loads(self.args[Constant.LDAP_GROUP_SEARCH_RETURN_ATTRS_KEY]) return_attributes_map = dict(zip(return_attributes_standard, return_attributes_actual)) ctls = SearchControls() ctls.setReturningAttributes(return_attributes_actual) ctls.setSearchScope(SearchControls.SUBTREE_SCOPE) ldap_records = [] org_units = json.loads(self.args[Constant.LDAP_GROUP_SEARCH_DOMAINS_KEY]) for search_unit in org_units: results = ctx.search(search_unit, search_target, ctls) for r in results: person_attributes = r.getAttributes() group = person_attributes.get(return_attributes_map['group_id']).get(0) group = re.sub(r"\r|\n", '', group).strip().encode('utf8') # skip special group that contains all group users if group == 'users': continue members = person_attributes.get(return_attributes_map['member_ids']) if members: self.group_map[group] = members sort_id = 0 for member in members.getAll(): member = re.sub(r"\r|\n", '', member).strip().encode('utf8') ldap_group_tuple = [self.group_app_id] ldap_group_tuple.append(group) ldap_group_tuple.append(sort_id) if member in self.ldap_user: ldap_group_tuple.append(self.app_id) else: ldap_group_tuple.append(self.group_app_id) ldap_group_tuple.append(member) ldap_group_tuple.append(self.wh_exec_id) ldap_records.append(ldap_group_tuple) sort_id += 1 else: pass self.logger.info("%d records found in group accounts" % (len(self.group_map))) csv_writer = csv.writer(open(file, "w"), delimiter='\x1a', quoting=csv.QUOTE_MINIMAL, lineterminator="\n") csv_writer.writerows(ldap_records)
def __init__(self, *arg): """ Return Surface that is subclassed from java.awt.image.BufferedImage. Alternative arguments: * Size (w,h) of surface, optional second argument of flags (SRCALPHA) * Bufferedimage to convert to Surface Module initialization places pyj2d.Surface in module's namespace. """ try: width, height = arg[0] try: if arg[1] & (BufferedImage.TYPE_INT_ARGB | Const.SRCALPHA): BufferedImage.__init__(self, width, height, BufferedImage.TYPE_INT_ARGB) else: BufferedImage.__init__(self, width, height, BufferedImage.TYPE_INT_RGB) except IndexError: BufferedImage.__init__(self, width, height, BufferedImage.TYPE_INT_ARGB) graphics2D = self.createGraphics() graphics2D.setColor(Color(0,0,0)) graphics2D.fillRect(0, 0, width, height) graphics2D.dispose() except TypeError: try: cm = arg[0].getColorModel() raster = arg[0].getRaster() isRasterPremultiplied = arg[0].isAlphaPremultiplied() properties = Hashtable() keys = arg[0].getPropertyNames() if keys != None: for key in keys: properties.put(key,arg[0].getProperty(key)) except AttributeError: cm, raster, isRasterPremultiplied, properties = arg BufferedImage.__init__(self, cm, raster, isRasterPremultiplied, properties) self._display = None #display surface self._super_surface = None self._offset = (0,0) self._colorkey = None self._nonimplemented_methods()
def main(): try: record = "A" if("record_type" in globals()): record = str(record_type) timer = Timer() env = Hashtable() env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory") env.put("java.naming.provider.url", "dns://" + dns_server) ictx = InitialDirContext(env) attrs = ictx.getAttributes(hostname, [record]) attr = attrs.get(record) result.value = timer.stop() result.status = result.STATUS_GOOD result.msg = "Query result: " + attr.toString() ictx.close() except NamingException, e: ictx.close() result.status = result.STATUS_FAILED result.msg = str(e.getMessage())
def ejecutaOSB(userAdmin, passAdmin, portAdmin, hostnameAdmin, ambiente): now = datetime.datetime.now() sessionName = "SesionScriptOSB_"+str(now.day)+"_"+str(now.month)+"_"+str(now.year)+"_"+ambiente print "t3", hostnameAdmin, portAdmin, "/jndi/" + DomainRuntimeServiceMBean.MBEANSERVER_JNDI_NAME serviceURL = JMXServiceURL("t3", hostnameAdmin, int(portAdmin), "/jndi/" + DomainRuntimeServiceMBean.MBEANSERVER_JNDI_NAME) h = Hashtable() h.put(Context.SECURITY_PRINCIPAL, userAdmin) h.put(Context.SECURITY_CREDENTIALS, passAdmin) h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote") conn = JMXConnectorFactory.connect(serviceURL, h) arregloAllProject = [] arregloAllProxy = [] arregloAllBS = [] arregloAllServicesURI = [] arregloAllDependentS = [] mbconn = conn.getMBeanServerConnection() sm = JMX.newMBeanProxy(mbconn, ObjectName.getInstance(SessionManagementMBean.OBJECT_NAME), SessionManagementMBean) sm.createSession(sessionName) configMBean = JMX.newMBeanProxy(mbconn, ObjectName.getInstance("com.bea:Name=" + ALSBConfigurationMBean.NAME + "." + sessionName + ",Type=" + ALSBConfigurationMBean.TYPE), ALSBConfigurationMBean) print "##############################" print "###Se genera conexion a OSB###" print "##############################" arregloAllProject=displayAllProjectsAndServices(ambiente, configMBean) arregloAllProxy=getAllProxyServices(ambiente, configMBean) arregloAllBS=getAllBusinessServices(ambiente, configMBean) arregloAllServicesURI=getAllServiceURIs(ambiente, configMBean) arregloAllDependentS=getDependentServices(ambiente, configMBean) sm.discardSession(sessionName) conn.close() return arregloAllProject, arregloAllProxy, arregloAllBS, arregloAllServicesURI, arregloAllDependentS
def __init__(self,url): env = Hashtable() env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory") env.put(Context.SECURITY_AUTHENTICATION, "none") env.put(Context.PROVIDER_URL, url) ctx = InitialDirContext(env) self.ctx = ctx
def initConnection(hostname, port, username, password): serviceURL = JMXServiceURL("t3", hostname, port,"/jndi/" + DomainRuntimeServiceMBean.MBEANSERVER_JNDI_NAME) h=Hashtable() h.put(Context.SECURITY_PRINCIPAL, username) h.put(Context.SECURITY_CREDENTIALS, password) h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote") return JMXConnectorFactory.connect(serviceURL, h)
def test_hashtable(self): x = Hashtable() x.put('a', 1) x.put('b', 2) x.put('c', 3) x.put((1,2), "xyz") y = dict(x) self.assertEqual(set(y.items()), set([('a', 1), ('b', 2), ('c', 3), ((1,2), "xyz")]))
def __init__(self, url): env = Hashtable() env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory") env.put(Context.SECURITY_AUTHENTICATION, "none") env.put(Context.PROVIDER_URL, url) ctx = InitialDirContext(env) self.ctx = ctx
def ssh(host, usr, pwd, timeout): jsch = JSch() session = jsch.getSession(usr, host, 22) session.setPassword(pwd) config = Hashtable() config.put('StrictHostKeyChecking', 'no') session.setConfig(config) session.setDaemonThread(True) ''' connect timeout ''' session.connect(timeout*1000) channel = session.openChannel('shell') channel.setPtyType('vt102') env = Hashtable() channel.setEnv(env) expect4j = Expect4j(channel.getInputStream(), channel.getOutputStream()) ''' expect return timeout ''' channel.connect(timeout*1000) return expect4j
def copy(self): """ Return Surface that is a copy of this surface. """ if not self._super_surface: img_properties = Hashtable() keys = self.getPropertyNames() if keys != None: for key in keys: img_properties.put(key,self.getProperty(key)) surface = Surface( self.getColorModel(), self.getData(), self.isAlphaPremultiplied(), img_properties ) surface._colorkey = self._colorkey else: surface = Surface((self.width,self.height), BufferedImage.TYPE_INT_ARGB) g2d = surface.createGraphics() g2d.drawImage(self, 0, 0, None) g2d.dispose() surface._colorkey = self._colorkey return surface
def createLdapContext(cls): Log.logMsg(5, "Creating ldap context") if cls.cf is None: raise Exception("Ldap not initialized") env=Hashtable() env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory") env.put(Context.PROVIDER_URL, 'ldapi:///opt/zimbra/openldap/var/run/ldapi/') env.put(Context.SECURITY_AUTHENTICATION, "simple") env.put(Context.SECURITY_PRINCIPAL, "cn=config") env.put(Context.SECURITY_CREDENTIALS, cls.cf.ldap_root_password) cls.mLdapContext = InitialDirContext(env) if cls.cf.ldap_is_master: #s = SearchControls() #s.setSearchScope(SearchControls.OBJECT_SCOPE) Log.logMsg(5, "Creating ldap context") ats = BasicAttributes("objectClass", None) atr = ['1.1'] results = cls.mLdapContext.search("cn=accesslog", ats, atr) if results.hasMore(): Log.logMsg(5, "Ldap config is master") cls.master = True
# Jython Database Specification API 2.0 # # $Id: jndi.py 1962 2001-12-14 04:20:03Z bzimmer $ # # Copyright (c) 2001 brian zimmer <*****@*****.**> """ This script is used to bind a JNDI reference for testing purposes only. """ from java.util import Hashtable from org.gjt.mm.mysql import MysqlDataSource from javax.naming import Context, InitialContext, NameAlreadyBoundException env = Hashtable() env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory") ds = MysqlDataSource() ds.setServerName("localhost") ds.setDatabaseName("ziclix") ds.setPort(3306) ctx = InitialContext(env) try: try: ctx.bind("/jdbc/mysqldb", ds) except NameAlreadyBoundException, e: ctx.unbind("/jdbc/mysqldb") ctx.bind("/jdbc/mysqldb", ds) finally: ctx.close()
# Jython Database Specification API 2.0 # # $Id: jndi.py,v 1.1 2001/12/14 04:20:03 bzimmer Exp $ # # Copyright (c) 2001 brian zimmer <*****@*****.**> """ This script is used to bind a JNDI reference for testing purposes only. """ from java.util import Hashtable from org.gjt.mm.mysql import MysqlDataSource from javax.naming import Context, InitialContext, NameAlreadyBoundException env = Hashtable() env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory") ds = MysqlDataSource() ds.setServerName("localhost") ds.setDatabaseName("ziclix") ds.setPort(3306) ctx = InitialContext(env) try: try: ctx.bind("/jdbc/mysqldb", ds) except NameAlreadyBoundException, e: ctx.unbind("/jdbc/mysqldb") ctx.bind("/jdbc/mysqldb", ds) finally: ctx.close()
writer = WriteMsgToFile(HOME_FILE) while True: try: delivery = consumer.nextDelivery() message = delivery.getBody() message = StringUtil.fromBytes(message) token = message.split(":",1)[0] rest = message.split(":",1)[1] message = str(message) # If message is a "token_request", process request and add new token to hashmap if message[0:13] == ("TOKEN_REQUEST"): makeToken = ProcessTokenRequest(message, channel) tokenID = makeToken.sendToken() permissions.put(tokenID[0], tokenID[1]) # Otherwise, check if message has valid token (token in hashmap). # If so, accept message, then delete token from valid list. else: if permissions.containsKey(token): print (" [x] Received '" + rest + "' from: " + permissions.get(token)) writer.writeMsg(rest, permissions.get(token)) #Write message to text file permissions.remove(token) else: print " ERROR: INVALID TOKEN PROVIDED IN MESSAGE" except BaseException: print "Consumer encountered an exception." channel.queueDelete(queueName) channel.close() connection.close()
def to_hashtable(dict): ht = Hashtable() for k in dict: ht.put(k, dict[k]) return ht
def __init__(self): # Setup controls - buttons first self.playButton.preferredSize = self.refreshButton.preferredSize self.playButton.actionCommand = self.PLAY self.playButton.actionPerformed = self.whenButtonClicked self.pauseButton.preferredSize = self.refreshButton.preferredSize self.pauseButton.actionCommand = self.PAUSE self.pauseButton.actionPerformed = self.whenButtonClicked self.stopButton.preferredSize = self.refreshButton.preferredSize self.stopButton.actionCommand = self.STOP self.stopButton.actionPerformed = self.whenButtonClicked self.refreshButton.actionCommand = self.REFRESH self.refreshButton.actionPerformed = self.whenButtonClicked # Now combobox and text field self.sourceCombo.itemStateChanged = self.whenSourceChanged self.updateSourcesList() self.rangeSpinner.stateChanged = self.whenRangeChanged # Now sliders ticksMajor = int(self.posMinMax / 4) ticksMinor = int(ticksMajor / 5) labels = Hashtable(3) labels.put(-self.posMinMax, JLabel("Left")) labels.put(0, JLabel("Centre")) labels.put(self.posMinMax, JLabel("Right")) self.positionXSlider.labelTable = labels self.positionXSlider.minimum = -self.posMinMax self.positionXSlider.maximum = self.posMinMax self.positionXSlider.majorTickSpacing = ticksMajor self.positionXSlider.minorTickSpacing = ticksMinor self.positionXSlider.paintTicks = True self.positionXSlider.paintLabels = True self.positionXSlider.snapToTicks = True self.positionXSlider.value = 0 self.positionXSlider.stateChanged = self.whenSliderXChanged labels = Hashtable(3) labels.put(-self.posMinMax, JLabel("Behind")) labels.put(0, JLabel("Centre")) labels.put(self.posMinMax, JLabel("In-front")) self.positionYSlider.labelTable = labels self.positionYSlider.minimum = -self.posMinMax self.positionYSlider.maximum = self.posMinMax self.positionYSlider.majorTickSpacing = ticksMajor self.positionYSlider.minorTickSpacing = ticksMinor self.positionYSlider.paintTicks = True self.positionYSlider.paintLabels = True self.positionYSlider.snapToTicks = True self.positionYSlider.value = 0 self.positionYSlider.orientation = JSlider.VERTICAL self.positionYSlider.stateChanged = self.whenSliderYChanged labels = Hashtable(3) labels.put(-self.posMinMax, JLabel("Below")) labels.put(0, JLabel("Centre")) labels.put(self.posMinMax, JLabel("Above")) self.positionZSlider.labelTable = labels self.positionZSlider.minimum = -self.posMinMax self.positionZSlider.maximum = self.posMinMax self.positionZSlider.majorTickSpacing = ticksMajor self.positionZSlider.minorTickSpacing = ticksMinor self.positionZSlider.paintTicks = True self.positionZSlider.paintLabels = True self.positionZSlider.snapToTicks = True self.positionZSlider.value = 0 self.positionZSlider.orientation = JSlider.VERTICAL self.positionZSlider.stateChanged = self.whenSliderZChanged # Setup frame self.title = "Simple JMRI Audio Player" self.contentPane.layout = BoxLayout(self.contentPane, BoxLayout.Y_AXIS) # Add controls to frame - combo & buttons first p = JPanel(FlowLayout(FlowLayout.LEADING)) p.add(self.sourceCombo) p.add(self.refreshButton) p.add(self.playButton) p.add(self.pauseButton) p.add(self.stopButton) #p.add(JLabel("Range")) #p.add(self.rangeSpinner) self.add(p) self.add(Box.createVerticalGlue()) # Now sliders p = JPanel(FlowLayout(FlowLayout.LEADING)) label = JLabel("Y Position") label.UI = VerticalLabelUI() # Default behaviour is anti-clockwise p.add(label) p.add(self.positionYSlider) p2 = JPanel() p2.layout = BoxLayout(p2, BoxLayout.Y_AXIS) p3 = JPanel() p3.add(JLabel("Range")) p3.add(self.rangeSpinner) p2.add(p3) #p2.add(Box.createVerticalGlue()) p3 = JPanel() p3.layout = BoxLayout(p3, BoxLayout.Y_AXIS) label = JLabel("X Position") label.alignmentX = JLabel.CENTER_ALIGNMENT p3.add(label) p3.add(self.positionXSlider) p2.add(p3) p.add(p2) label = JLabel("Z Position") label.UI = VerticalLabelUI() p.add(label) p.add(self.positionZSlider) self.add(p) # Finally pack and show self.pack() self.show()
from oracle.soa.management.facade import LocatorFactory from oracle.soa.management.util import ReferenceFilter from oracle.soa.management.util import ReferenceFilter host = '' # Change according to your env port = '8001' # Change according to your env username = '******' # Change according to your env password = '' # Change according to your env providerURL = "t3://" + host + ":" + port + "/soa-infra" print providerURL mbeanRuntime = "weblogic.management.mbeanservers.runtime" jmxProtoProviderPackages = "weblogic.management.remote" mBeanName = "oracle.soa.config:Application=soa-infra,j2eeType=CompositeLifecycleConfig,name=soa-infra" jndiProps = Hashtable() jndiProps.put(Context.PROVIDER_URL, providerURL) jndiProps.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory") jndiProps.put(Context.SECURITY_PRINCIPAL, username) jndiProps.put(Context.SECURITY_CREDENTIALS, password) myLocator = LocatorFactory.createLocator(jndiProps) jmxurl = "service:jmx:t3://" + host + ":" + port + "/jndi/" + mbeanRuntime serviceURL = JMXServiceURL(jmxurl) ht = Hashtable() ht.put("java.naming.security.principal", username) ht.put("java.naming.security.credentials", password) ht.put("jmx.remote.protocol.provider.pkgs", jmxProtoProviderPackages) jmxConnector = JMXConnectorFactory.newJMXConnector(serviceURL, ht) jmxConnector.connect() mbsc = jmxConnector.getMBeanServerConnection()
def __init__(self): # Setup controls - buttons first self.playButton.preferredSize = self.refreshButton.preferredSize self.playButton.actionCommand = self.PLAY self.playButton.actionPerformed = self.whenButtonClicked self.pauseButton.preferredSize = self.refreshButton.preferredSize self.pauseButton.actionCommand = self.PAUSE self.pauseButton.actionPerformed = self.whenButtonClicked self.stopButton.preferredSize = self.refreshButton.preferredSize self.stopButton.actionCommand = self.STOP self.stopButton.actionPerformed = self.whenButtonClicked self.refreshButton.actionCommand = self.REFRESH self.refreshButton.actionPerformed = self.whenButtonClicked # Now combobox and text field self.sourceCombo.itemStateChanged = self.whenSourceChanged self.updateSourcesList() self.rangeSpinner.stateChanged = self.whenRangeChanged # Now sliders ticksMajor = int(self.posMinMax/4) ticksMinor = int(ticksMajor/5) labels = Hashtable(3) labels.put(-self.posMinMax, JLabel("Left")) labels.put( 0, JLabel("Centre")) labels.put( self.posMinMax, JLabel("Right")) self.positionXSlider.labelTable = labels self.positionXSlider.minimum = -self.posMinMax self.positionXSlider.maximum = self.posMinMax self.positionXSlider.majorTickSpacing = ticksMajor self.positionXSlider.minorTickSpacing = ticksMinor self.positionXSlider.paintTicks = True self.positionXSlider.paintLabels = True self.positionXSlider.snapToTicks = True self.positionXSlider.value = 0 self.positionXSlider.stateChanged = self.whenSliderXChanged labels = Hashtable(3) labels.put(-self.posMinMax, JLabel("Behind")) labels.put( 0, JLabel("Centre")) labels.put( self.posMinMax, JLabel("In-front")) self.positionYSlider.labelTable = labels self.positionYSlider.minimum = -self.posMinMax self.positionYSlider.maximum = self.posMinMax self.positionYSlider.majorTickSpacing = ticksMajor self.positionYSlider.minorTickSpacing = ticksMinor self.positionYSlider.paintTicks = True self.positionYSlider.paintLabels = True self.positionYSlider.snapToTicks = True self.positionYSlider.value = 0 self.positionYSlider.orientation = JSlider.VERTICAL self.positionYSlider.stateChanged = self.whenSliderYChanged labels = Hashtable(3) labels.put(-self.posMinMax, JLabel("Below")) labels.put( 0, JLabel("Centre")) labels.put( self.posMinMax, JLabel("Above")) self.positionZSlider.labelTable = labels self.positionZSlider.minimum = -self.posMinMax self.positionZSlider.maximum = self.posMinMax self.positionZSlider.majorTickSpacing = ticksMajor self.positionZSlider.minorTickSpacing = ticksMinor self.positionZSlider.paintTicks = True self.positionZSlider.paintLabels = True self.positionZSlider.snapToTicks = True self.positionZSlider.value = 0 self.positionZSlider.orientation = JSlider.VERTICAL self.positionZSlider.stateChanged = self.whenSliderZChanged # Setup frame self.title = "Simple JMRI Audio Player" self.contentPane.layout = BoxLayout(self.contentPane, BoxLayout.Y_AXIS) # Add controls to frame - combo & buttons first p = JPanel(FlowLayout(FlowLayout.LEADING)) p.add(self.sourceCombo) p.add(self.refreshButton) p.add(self.playButton) p.add(self.pauseButton) p.add(self.stopButton) #p.add(JLabel("Range")) #p.add(self.rangeSpinner) self.add(p) self.add(Box.createVerticalGlue()) # Now sliders p = JPanel(FlowLayout(FlowLayout.LEADING)) label = JLabel("Y Position") label.UI = VerticalLabelUI() # Default behaviour is anti-clockwise p.add(label) p.add(self.positionYSlider) p2 = JPanel() p2.layout = BoxLayout(p2, BoxLayout.Y_AXIS) p3 = JPanel() p3.add(JLabel("Range")) p3.add(self.rangeSpinner) p2.add(p3) #p2.add(Box.createVerticalGlue()) p3 = JPanel() p3.layout = BoxLayout(p3, BoxLayout.Y_AXIS) label = JLabel("X Position") label.alignmentX = JLabel.CENTER_ALIGNMENT p3.add(label) p3.add(self.positionXSlider) p2.add(p3) p.add(p2) label = JLabel("Z Position") label.UI = VerticalLabelUI() p.add(label) p.add(self.positionZSlider) self.add(p) # Finally pack and show self.pack() self.show()
writer = WriteMsgToFile(HOME_FILE) while True: try: delivery = consumer.nextDelivery() message = delivery.getBody() message = StringUtil.fromBytes(message) token = message.split(":", 1)[0] rest = message.split(":", 1)[1] message = str(message) # If message is a "token_request", process request and add new token to hashmap if message[0:13] == ("TOKEN_REQUEST"): makeToken = ProcessTokenRequest(message, channel) tokenID = makeToken.sendToken() permissions.put(tokenID[0], tokenID[1]) # Otherwise, check if message has valid token (token in hashmap). # If so, accept message, then delete token from valid list. else: if permissions.containsKey(token): print(" [x] Received '" + rest + "' from: " + permissions.get(token)) writer.writeMsg( rest, permissions.get(token)) #Write message to text file permissions.remove(token) else: print " ERROR: INVALID TOKEN PROVIDED IN MESSAGE" except BaseException: print "Consumer encountered an exception." channel.queueDelete(queueName)
def __init__(self,url,user,pwd,proto): env=Hashtable() env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory") env.put(Context.SECURITY_AUTHENTICATION,"simple") env.put(Context.PROVIDER_URL,url) env.put(Context.SECURITY_PRINCIPAL,user) env.put(Context.SECURITY_CREDENTIALS,pwd) if proto is not None: env.put(Context.SECURITY_PROTOCOL,proto) ctx=InitialDirContext(env) self.url=url self.ctx=ctx
def fetch_ldap_user(self, file): """ fetch ldap user from ldap server :param file: output file name """ self.logger.info("Fetching ldap users") # Setup LDAP Context Options settings = Hashtable() settings.put(Context.INITIAL_CONTEXT_FACTORY, self.args[Constant.LDAP_CONTEXT_FACTORY_KEY]) settings.put(Context.PROVIDER_URL, self.args[Constant.LDAP_CONTEXT_PROVIDER_URL_KEY]) settings.put(Context.SECURITY_PRINCIPAL, self.args[Constant.LDAP_CONTEXT_SECURITY_PRINCIPAL_KEY]) settings.put(Context.SECURITY_CREDENTIALS, self.args[Constant.LDAP_CONTEXT_SECURITY_CREDENTIALS_KEY]) # page the result, each page have fix number of records pageSize = 5000 pageControl = PagedResultsControl(pageSize, Control.NONCRITICAL) c_array = array([pageControl], Control) # Connect to LDAP Server ctx = InitialLdapContext(settings, None) ctx.setRequestControls(c_array) # load the java Hashtable out of the ldap server # Query starting point and query target search_target = '(objectClass=person)' return_attributes_standard = [ 'user_id', 'distinct_name', 'name', 'display_name', 'title', 'employee_number', 'manager', 'mail', 'department_number', 'department', 'start_date', 'mobile' ] return_attributes_actual = json.loads( self.args[Constant.LDAP_SEARCH_RETURN_ATTRS_KEY]) return_attributes_map = dict( zip(return_attributes_standard, return_attributes_actual)) ctls = SearchControls() ctls.setReturningAttributes(return_attributes_actual) ctls.setSearchScope(SearchControls.SUBTREE_SCOPE) ldap_records = [] # domain format should look like : ['OU=domain1','OU=domain2','OU=domain3,OU=subdomain3'] org_units = json.loads(self.args[Constant.LDAP_SEARCH_DOMAINS_KEY]) cookie = None for search_unit in org_units: # pagination while True: # do the search search_result = ctx.search(search_unit, search_target, ctls) for person in search_result: ldap_user_tuple = [self.app_id] if search_unit == self.args[ Constant.LDAP_INACTIVE_DOMAIN_KEY]: ldap_user_tuple.append('N') else: ldap_user_tuple.append('Y') person_attributes = person.getAttributes() user_id = person_attributes.get( return_attributes_map['user_id']) user_id = re.sub(r"\r|\n", '', user_id.get(0)).strip().encode('utf8') self.ldap_user.add(user_id) for attr_name in return_attributes_actual: attr = person_attributes.get(attr_name) if attr: attr = re.sub(r"\r|\n", '', attr.get(0)).strip().encode('utf8') # special fix for start_date if attr_name == return_attributes_map[ 'start_date'] and len(attr) == 4: attr += '0101' ldap_user_tuple.append(attr) else: ldap_user_tuple.append("") ldap_user_tuple.append(self.wh_exec_id) ldap_records.append(ldap_user_tuple) # Examine the paged results control response control = ctx.getResponseControls()[ 0] # will always return a list, but only have one item if isinstance(control, PagedResultsResponseControl): cookie = control.getCookie() # Re-activate paged results if cookie is None: # reset ctx, break while loop, do next search pageControl = PagedResultsControl(pageSize, Control.NONCRITICAL) c_array = array([pageControl], Control) ctx.setRequestControls(c_array) break else: self.logger.debug( "Have more than one page of result when search " + search_unit) pageControl = PagedResultsControl(pageSize, cookie, Control.CRITICAL) c_array = array([pageControl], Control) ctx.setRequestControls(c_array) self.logger.info("%d records found in ldap search" % (len(self.ldap_user))) csv_writer = csv.writer(open(file, "w"), delimiter='\x1a', quoting=csv.QUOTE_MINIMAL, lineterminator="\n") csv_writer.writerows(ldap_records)
def fetch_ldap_user(self, file): """ fetch ldap user from ldap server :param file: output file name """ # Setup LDAP Context Options settings = Hashtable() settings.put(Context.INITIAL_CONTEXT_FACTORY, self.args[Constant.LDAP_CONTEXT_FACTORY_KEY]) settings.put(Context.PROVIDER_URL, self.args[Constant.LDAP_CONTEXT_PROVIDER_URL_KEY]) settings.put(Context.SECURITY_PRINCIPAL, self.args[Constant.LDAP_CONTEXT_SECURITY_PRINCIPAL_KEY]) settings.put(Context.SECURITY_CREDENTIALS, self.args[Constant.LDAP_CONTEXT_SECURITY_CREDENTIALS_KEY]) # Connect to LDAP Server ctx = InitialDirContext(settings) # load the java Hashtable out of the ldap server # Query starting point and query target search_target = '(objectClass=person)' return_attributes_standard = ['user_id', 'distinct_name', 'name', 'display_name', 'title', 'employee_number', 'manager', 'mail', 'department_number', 'department', 'start_date', 'mobile'] return_attributes_actual = self.split_property(self.args[Constant.LDAP_SEARCH_RETURN_ATTRS_KEY]) return_attributes_map = dict(zip(return_attributes_standard, return_attributes_actual)) ctls = SearchControls() ctls.setReturningAttributes(return_attributes_actual) ctls.setSearchScope(SearchControls.SUBTREE_SCOPE) ldap_records = [] # domain format should look like : 'OU=domain1','OU=domain2','OU=domain3,OU=subdomain3' org_units = self.split_property(self.args[Constant.LDAP_SEARCH_DOMAINS_KEY]) for search_unit in org_units: search_result = ctx.search(search_unit, search_target, ctls) # print search_return_attributes for person in search_result: ldap_user_tuple = [self.app_id] if search_unit == self.args[Constant.LDAP_INACTIVE_DOMAIN_KEY]: ldap_user_tuple.append('N') else: ldap_user_tuple.append('Y') person_attributes = person.getAttributes() user_id = person_attributes.get(return_attributes_map['user_id']) user_id = re.sub(r"\r|\n", '', user_id.get(0)).strip().encode('utf8') self.ldap_user.add(user_id) for attr_name in return_attributes_actual: attr = person_attributes.get(attr_name) if attr: attr = re.sub(r"\r|\n", '', attr.get(0)).strip().encode('utf8') # special fix for start_date if attr_name == return_attributes_map['start_date'] and len(attr) == 4: attr += '0101' ldap_user_tuple.append(attr) else: ldap_user_tuple.append("") ldap_user_tuple.append(self.wh_exec_id) ldap_records.append(ldap_user_tuple) self.logger.info("%d records found in ldap search" % (len(self.ldap_user))) csv_writer = csv.writer(open(file, "w"), delimiter='\x1a', quoting=csv.QUOTE_MINIMAL, lineterminator="\n") csv_writer.writerows(ldap_records)
def create_hashtable(dictionary): ht = Hashtable() for key, value in dictionary.items(): ht.put(key, value) return ht
def fetch_ldap_user(self, file): """ fetch ldap user from ldap server :param file: output file name """ # Setup LDAP Context Options settings = Hashtable() settings.put(Context.INITIAL_CONTEXT_FACTORY, self.args[Constant.LDAP_CONTEXT_FACTORY_KEY]) settings.put(Context.PROVIDER_URL, self.args[Constant.LDAP_CONTEXT_PROVIDER_URL_KEY]) settings.put(Context.SECURITY_PRINCIPAL, self.args[Constant.LDAP_CONTEXT_SECURITY_PRINCIPAL_KEY]) settings.put(Context.SECURITY_CREDENTIALS, self.args[Constant.LDAP_CONTEXT_SECURITY_CREDENTIALS_KEY]) # Connect to LDAP Server ctx = InitialDirContext(settings) # load the java Hashtable out of the ldap server # Query starting point and query target search_target = '(objectClass=person)' return_attributes_standard = [ 'user_id', 'distinct_name', 'name', 'display_name', 'title', 'employee_number', 'manager', 'mail', 'department_number', 'department', 'start_date', 'mobile' ] return_attributes_actual = self.split_property( self.args[Constant.LDAP_SEARCH_RETURN_ATTRS_KEY]) return_attributes_map = dict( zip(return_attributes_standard, return_attributes_actual)) ctls = SearchControls() ctls.setReturningAttributes(return_attributes_actual) ctls.setSearchScope(SearchControls.SUBTREE_SCOPE) ldap_records = [] # domain format should look like : 'OU=domain1','OU=domain2','OU=domain3,OU=subdomain3' org_units = self.split_property( self.args[Constant.LDAP_SEARCH_DOMAINS_KEY]) for search_unit in org_units: search_result = ctx.search(search_unit, search_target, ctls) # print search_return_attributes for person in search_result: ldap_user_tuple = [self.app_id] if search_unit == self.args[Constant.LDAP_INACTIVE_DOMAIN_KEY]: ldap_user_tuple.append('N') else: ldap_user_tuple.append('Y') person_attributes = person.getAttributes() user_id = person_attributes.get( return_attributes_map['user_id']) user_id = re.sub(r"\r|\n", '', user_id.get(0)).strip().encode('utf8') self.ldap_user.add(user_id) for attr_name in return_attributes_actual: attr = person_attributes.get(attr_name) if attr: attr = re.sub(r"\r|\n", '', attr.get(0)).strip().encode('utf8') # special fix for start_date if attr_name == return_attributes_map[ 'start_date'] and len(attr) == 4: attr += '0101' ldap_user_tuple.append(attr) else: ldap_user_tuple.append("") ldap_user_tuple.append(self.wh_exec_id) ldap_records.append(ldap_user_tuple) self.logger.info("%d records found in ldap search" % (len(self.ldap_user))) csv_writer = csv.writer(open(file, "w"), delimiter='\x1a', quoting=csv.QUOTE_MINIMAL, lineterminator="\n") csv_writer.writerows(ldap_records)
def fetch_ldap_user(self, file): """ fetch ldap user from ldap server :param file: output file name """ # Setup LDAP Context Options settings = Hashtable() settings.put(Context.INITIAL_CONTEXT_FACTORY, self.args[Constant.LDAP_CONTEXT_FACTORY_KEY]) settings.put(Context.PROVIDER_URL, self.args[Constant.LDAP_CONTEXT_PROVIDER_URL_KEY]) settings.put(Context.SECURITY_PRINCIPAL, self.args[Constant.LDAP_CONTEXT_SECURITY_PRINCIPAL_KEY]) settings.put(Context.SECURITY_CREDENTIALS, self.args[Constant.LDAP_CONTEXT_SECURITY_CREDENTIALS_KEY]) # page the result, each page have fix number of records pageSize = 5000 pageControl = PagedResultsControl(pageSize, Control.NONCRITICAL) c_array = array([pageControl], Control) # Connect to LDAP Server ctx = InitialLdapContext(settings, None) ctx.setRequestControls(c_array) # load the java Hashtable out of the ldap server # Query starting point and query target search_target = '(objectClass=person)' return_attributes_standard = ['user_id', 'distinct_name', 'name', 'display_name', 'title', 'employee_number', 'manager', 'mail', 'department_number', 'department', 'start_date', 'mobile'] return_attributes_actual = json.loads(self.args[Constant.LDAP_SEARCH_RETURN_ATTRS_KEY]) return_attributes_map = dict(zip(return_attributes_standard, return_attributes_actual)) ctls = SearchControls() ctls.setReturningAttributes(return_attributes_actual) ctls.setSearchScope(SearchControls.SUBTREE_SCOPE) ldap_records = [] # domain format should look like : ['OU=domain1','OU=domain2','OU=domain3,OU=subdomain3'] org_units = json.loads(self.args[Constant.LDAP_SEARCH_DOMAINS_KEY]) cookie = None for search_unit in org_units: # pagination while True: # do the search search_result = ctx.search(search_unit, search_target, ctls) for person in search_result: ldap_user_tuple = [self.app_id] if search_unit == self.args[Constant.LDAP_INACTIVE_DOMAIN_KEY]: ldap_user_tuple.append('N') else: ldap_user_tuple.append('Y') person_attributes = person.getAttributes() user_id = person_attributes.get(return_attributes_map['user_id']) user_id = re.sub(r"\r|\n", '', user_id.get(0)).strip().encode('utf8') self.ldap_user.add(user_id) for attr_name in return_attributes_actual: attr = person_attributes.get(attr_name) if attr: attr = re.sub(r"\r|\n", '', attr.get(0)).strip().encode('utf8') # special fix for start_date if attr_name == return_attributes_map['start_date'] and len(attr) == 4: attr += '0101' ldap_user_tuple.append(attr) else: ldap_user_tuple.append("") ldap_user_tuple.append(self.wh_exec_id) ldap_records.append(ldap_user_tuple) # Examine the paged results control response control = ctx.getResponseControls()[0] # will always return a list, but only have one item if isinstance(control, PagedResultsResponseControl): cookie = control.getCookie() # Re-activate paged results if cookie is None: # reset ctx, break while loop, do next search pageControl = PagedResultsControl(pageSize, Control.NONCRITICAL) c_array = array([pageControl], Control) ctx.setRequestControls(c_array) break else: self.logger.debug("Have more than one page of result when search " + search_unit) pageControl = PagedResultsControl(pageSize, cookie, Control.CRITICAL) c_array = array([pageControl], Control) ctx.setRequestControls(c_array) self.logger.info("%d records found in ldap search" % (len(self.ldap_user))) csv_writer = csv.writer(open(file, "w"), delimiter='\x1a', quoting=csv.QUOTE_MINIMAL, lineterminator="\n") csv_writer.writerows(ldap_records)
def _create_hashtable(dictionary): ht = Hashtable() for key, value in dictionary.items(): ht.put(key, value) return ht