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 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 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 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 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 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 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 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 __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 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 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 __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 __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)
class TcpDbUtils(discoverydbutils.DiscoveryDbUtils): CONTEXT = 'tcpdiscovery' TCP_EXECUTED_JOBS = Hashtable() def __init__(self, Framework): discoverydbutils.DiscoveryDbUtils.__init__(self, Framework, TcpDbUtils.CONTEXT) self.knownPortsConfigFile = Framework.getConfigFile( CollectorsParameters.KEY_COLLECTORS_SERVERDATA_PORTNUMBERTOPORTNAME ) self.applicSignConfigFile = Framework.getConfigFile( CollectorsParameters.KEY_COLLECTORS_SERVERDATA_APPLICATIONSIGNATURE ) self.hostID = Framework.getDestinationAttribute('hostId') globalSettings = GeneralSettingsConfigFile.getInstance() #hours self.TCP_EXPIRATION_PERIOD = globalSettings.getPropertyIntegerValue( 'tcpExpirationTime', 24) #milliseconds self.PORT_EXPIRATION_PERIOD = globalSettings.getPropertyIntegerValue( 'portExpirationTime', 60) * 1000L def addPortToProcess(self, ipaddress, port, process_pid, listen=0, prot=modeling.TCP_PROTOCOL, ProcessName=None): pid = -1 if process_pid != None: pid = int(process_pid) port2process = PortToProcess(self.hostID, ipaddress, int(port), pid, prot, listen, ProcessName) self.addToBulk(port2process) def flushPortToProcesses(self): self.executeUpdate( PortToProcess.DELETESQL % ('Port_Process', self.hostID, str(System.currentTimeMillis() - self.PORT_EXPIRATION_PERIOD))) self.executeBulk(PortToProcess.PORTTOPROCESSTYPE) TcpDbUtils.TCP_EXECUTED_JOBS.clear() def addTcpConnection(self, srcAddr, srcPort, dstAddr, dstPort): tcpConnection = TcpConnection(self.hostID, srcAddr, dstAddr, srcPort, dstPort) self.addToBulk(tcpConnection) def flushTcpConnection(self): self.executeUpdate(TcpConnection.DELETESQL % ('Agg_V5', self.hostID, self.TCP_EXPIRATION_PERIOD)) self.executeBulk(TcpConnection.TCPCONNECTIONTYPE) TcpDbUtils.TCP_EXECUTED_JOBS.clear()
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 test_class_coercion(self): c = Coercions() from java.util import Hashtable, HashMap ht = Hashtable() hm = HashMap() ht['one'] = 'uno' hm['zwei'] = 'two' for obj, cls in ((ht, "java.util.Hashtable"), (hm, "java.util.HashMap"), ("abc", "java.lang.String"), (1, "java.lang.Integer"), (1.2, "java.lang.Double"), (Hashtable, "java.lang.Class")): self.assertEquals(c.tellClassNameSerializable(obj), "class " + cls) self.assertEquals(c.tellClassNameObject(ht), "class java.util.Hashtable")
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 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
def get_java_variables(DICT_1, DICT_2, DICT_3, LIST_1, LIST_2, LIST_3, **extra): return dict(STRING_0=String(), STRING_1=String('a'), STRING_2=String('ab'), STRING_3=String('abc'), HASHTABLE_0=Hashtable(), HASHTABLE_1=create_hashtable(DICT_1), HASHTABLE_2=create_hashtable(DICT_2), HASHTABLE_3=create_hashtable(DICT_3), VECTOR_0=Vector(), VECTOR_1=Vector(LIST_1), VECTOR_2=Vector(LIST_2), VECTOR_3=Vector(LIST_3), ARRAY_0=jarray.array([], String), ARRAY_1=jarray.array([str(i) for i in LIST_1], String), ARRAY_2=jarray.array([str(i) for i in LIST_2], String), ARRAY_3=jarray.array([str(i) for i in LIST_3], String))
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, interpreter, debugger, debugPanel): self.interpreter = interpreter self.debugger = debugger self.debugPanel = debugPanel # Build our slider! self.slider = JSlider(JSlider.HORIZONTAL, debugger.MIN_SPEED, debugger.MAX_SPEED, debugger.speed, stateChanged=self._sliderSpeedChanged) # Label the slider! self.sliderLabels = labels = Hashtable() labels.put(debugger.MIN_SPEED, JLabel("Slow")) labels.put(debugger.MAX_SPEED, JLabel("Fast")) self.slider.labelTable = labels self.slider.paintLabels = True # Build some buttons! self.buttonInsets = Insets(0, 0, 0, 0) self.watchButton = self.makeDebuggerButton( self.debugPanel.watchVariable, 'images/plus.jpg') self.unwatchButton = self.makeDebuggerButton( self.debugPanel.unwatchVariable, 'images/minus.jpg') self.fullspeedButton = self.makeDebuggerButton( self.debugPanel.fullSpeed, 'images/fullspeed.jpg') self.stopButton = self.makeDebuggerButton(self.interpreter.stopAction, 'images/stop.jpg') # Display them all! self.setLayout(BoxLayout(self, BoxLayout.X_AXIS)) self.add(self.slider) self.add(self.watchButton) self.add(self.unwatchButton) self.add(self.fullspeedButton) self.add(self.stopButton) # Connect the slider to the debugger! self.debugger.onSpeedSet.connect(self._showSpeedSetting) self.debugger.onStart.connect(self._lockControls) self.debugger.onStop.connect(self._unlockControls)
class NetlinksService: EXECUTED_JOBS = Hashtable() def __init__(self, Framework): self.Framework = Framework self.knownPortsConfigFile = self.Framework.getConfigFile( CollectorsParameters.KEY_COLLECTORS_SERVERDATA_PORTNUMBERTOPORTNAME ) self.includeOutscopeServers = self.getBooleanParameter( 'includeOutscopeServers') self.includeOutscopeClients = self.getBooleanParameter( 'includeOutscopeClients') self.ip2ports = HashMap() def discover(self): logger.debug('Starting netlinks discovery') jobFinished = 0 try: if tcpdbutils.shouldDiscoverTCP(self.Framework): self.discover_private() else: if logger.isInfoEnabled(): logger.info( 'No changes in netlinks database since previous job execution' ) jobFinished = 1 finally: if logger.isInfoEnabled(): logger.info('Netlinks discovery finished') if not jobFinished: #in this case we should clear already executed jobs from cache #to enable this job run once again tcpdbutils.resetShouldDiscoverTCP(self.Framework) def discover_private(self): raise NotImplementedError, "discover_private" def servicesPorts(self, onlyKnownPorts=1): services = self.Framework.getParameter('services') if logger.isDebugEnabled(): logger.debug('Requested services:', services) if (services == None) or (len(services) == 0) or (services == '*'): if onlyKnownPorts: portsInfo = self.knownPortsConfigFile.getTcpPorts() services = '' delimiter = '' for info in portsInfo: services = services + delimiter + str(info.getPortNumber()) delimiter = ',' if len(services) == 0: return services else: return '' names = services.split(',') ports = '' delimiter = '' for name in names: portNums = self.knownPortsConfigFile.getPortByName(name) if (portNums == None) or (len(portNums) == 0): try: portNums = [Integer.parseInt(name)] except: logger.debug('Failed to resolve service port number:', name) continue for portNum in portNums: ports = ports + delimiter + str(portNum) delimiter = ',' if logger.isDebugEnabled(): logger.debug('Requested services ports:', ports) return ports def isIpOutOfScope(self, addr): return DomainScopeManager.isIpOutOfScope(addr) def shouldInclude(self, addr, isServer): if self.isIpOutOfScope(addr): if isServer and (not self.includeOutscopeServers): return 0 if (not isServer) and (not self.includeOutscopeClients): return 0 return 1 def getBooleanParameter(self, paramName): paramVaue = self.getParameterValue(paramName) if paramVaue == None: return 0 return Boolean.parseBoolean(paramVaue) def getParameterValue(self, paramName): return self.Framework.getParameter(paramName) def createLinkID(self, ip1, ip2): return ip1 + '<=>' + ip2
def test_copy_java_hashtable(self): x = Hashtable() xc = x.copy() self.assertEqual(type(x), type(xc))
def test_hashtable_equal(self): for d in ({}, {1:2}): x = Hashtable(d) self.assertEqual(x, d) self.assertEqual(d, x) self.assertEqual(x, HashMap(d))
def test_hashtable_remove(self): x = Hashtable({}) with self.assertRaises(KeyError): del x[0]
def test_java_dict_likes_are_list_like(self): assert_equal(is_list_like(HashMap()), True) assert_equal(is_list_like(Hashtable()), True)
# 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()
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 create_hashtable(dictionary): ht = Hashtable() for key, value in dictionary.items(): ht.put(key, value) return ht
def to_hashtable(dict): ht = Hashtable() for k in dict: ht.put(k, dict[k]) return ht
from com.rabbitmq.client import QueueingConsumer # # Created by davidhua on 7/3/14. # broker = BrokerInfo() broker.setHost("localhost") broker.setUser("david2") broker.setPassword("123") broker.setPort(5672) # Port 5671 for ssl broker.setSSL(False) # True for no ssl HOME_FILE = "/var/netshell/users/admin" permissions = Hashtable() # Get name of queue to receive messages from from file. uuidQueue = UUIDManager(HOME_FILE) queueName = uuidQueue.checkUUID() # Create connection and queue factory = SSLConnection(broker).createConnection() connection = factory.newConnection() channel = connection.createChannel() channel.queueDeclare(queueName, False, False, True, None) try: consumer = QueueingConsumer(channel) # Declare as exclusive consumer of queue channel.basicConsume(queueName, True, "consumer", False, True, None,
list2 = ['a', 'b'] list3 = ['a', 'b', 'c'] dict0 = {} dict1 = {'a': 1} dict2 = {'a': 1, 'b': 2} dict3 = {'a': 1, 'b': 2, 'c': 3} custom0 = _Custom(0) custom1 = _Custom(1) custom2 = _Custom(2) custom3 = _Custom(3) length_method = _LengthMethod() size_method = _SizeMethod() length_attribute = _LengthAttribute() if os.name == 'java': string0 = String() string1 = String('a') string2 = String('ab') string3 = String('abc') hashtable0 = Hashtable() hashtable1 = _create_hashtable(dict1) hashtable2 = _create_hashtable(dict2) hashtable3 = _create_hashtable(dict3) vector0 = Vector() vector1 = Vector(list1) vector2 = Vector(list2) vector3 = Vector(list3) array0 = jarray.array(list0, String) array1 = jarray.array(list1, String) array2 = jarray.array(list2, String) array3 = jarray.array(list3, String)
from com.rabbitmq.client import QueueingConsumer # # Created by davidhua on 7/3/14. # broker = BrokerInfo() broker.setHost("localhost") broker.setUser("david2") broker.setPassword("123") broker.setPort(5672) # Port 5671 for ssl broker.setSSL(False) # True for no ssl HOME_FILE = "/var/netshell/users/admin" permissions = Hashtable() # Get name of queue to receive messages from from file. uuidQueue = UUIDManager(HOME_FILE) queueName = uuidQueue.checkUUID() # Create connection and queue factory = SSLConnection(broker).createConnection() connection = factory.newConnection() channel = connection.createChannel() channel.queueDeclare(queueName, False, False, True, None) try: consumer = QueueingConsumer(channel) # Declare as exclusive consumer of queue channel.basicConsume(queueName, True, "consumer", False, True, None, consumer)
# 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()
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 isEmpty(self): return Hashtable.isEmpty(self)
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 """ 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)
refs = bContext.getServiceReferences(str(AlgorithmFactory), filter) return refs def getAlgorithm(ref): if ref: return bContext.getService(ref) def getService(service): return bContext.getService(bContext.getServiceReference(str(service))) from org.cishell.framework.data import BasicData refs = findAlgorithms() factory = getAlgorithm(refs[2]) alg = factory.createAlgorithm([BasicData(None)],Hashtable(),ciContext) dm1 = alg.execute() dm2 = [BasicDataModel("100"),] factory = getAlgorithm(refs[0]) alg = factory.createAlgorithm(dm2,Hashtable(),ciContext) dm3 = alg.execute() factory = getAlgorithm(refs[1]) alg = factory.createAlgorithm(dm3,Hashtable(),ciContext) dm4 = alg.execute() # possible other commands from org.osgi.service.log import LogService log = getService(LogService)
def _create_hashtable(dictionary): ht = Hashtable() for key, value in dictionary.items(): ht.put(key, value) 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()
def test_java_maps(self): assert_equal(is_dict_like(HashMap()), True) assert_equal(is_dict_like(Hashtable()), True)
def DiscoveryMain(Framework): vector = ObjectStateHolderVector() protocol = Framework.getDestinationAttribute('Protocol') client = None shell = None try: try: # connect to destination client = Framework.createClient() # wrap client with Shell shell = shellutils.ShellFactory().createShell(client) except AuthenticationException, ae: errormessages.resolveAndReport(ae.getMessage(), protocol, Framework) except: exInfo = logger.prepareJythonStackTrace('') errormessages.resolveAndReport(exInfo, protocol, Framework) else: language = Framework.getDestinationAttribute('language') hostCmdbId = Framework.getDestinationAttribute('hostId') # configure internationalization support if language and language != 'NA': langBund = Framework.getEnvironmentInformation().getBundle( 'langHost_Resources_By_TTY', language) else: langBund = Framework.getEnvironmentInformation().getBundle( 'langHost_Resources_By_TTY') # discovery discoverCPUs = Boolean.parseBoolean( Framework.getParameter('discoverCPUs')) discoverDisks = Boolean.parseBoolean( Framework.getParameter('discoverDisks')) discoveriSCSIInfo = Boolean.parseBoolean( Framework.getParameter('discoveriSCSIInfo')) discoverDrivers = Boolean.parseBoolean( Framework.getParameter('discoverDrivers')) discoverMemory = Boolean.parseBoolean( Framework.getParameter('discoverMemory')) discoverSoftware = Boolean.parseBoolean( Framework.getParameter('discoverInstalledSoftware')) discoverUsers = Boolean.parseBoolean( Framework.getParameter('discoverUsers')) discoverServices = Boolean.parseBoolean( Framework.getParameter('discoverServices')) discoverShares = Boolean.parseBoolean( Framework.getParameter('discoverShares')) discoverP2P = Boolean.parseBoolean( Framework.getParameter('discoverP2P')) try: hostOsh = modeling.createOshByCmdbIdString('host', hostCmdbId) if discoverShares: try: vector.addAll(_discoverSharedResources(shell, hostOsh)) except: errorMessage = 'Failed to discover shared resources' _logWarn( errorcodes. FAILED_DISCOVERING_RESOURCE_WITH_CLIENT_TYPE, ['share', protocol], errorMessage) if discoverCPUs: try: vector.addAll( TTY_HR_CPU_Lib.disWinOS(hostCmdbId, shell, Framework, langBund)) except: errorMessage = 'Failed to discover CPUs' _logWarn( errorcodes. FAILED_DISCOVERING_RESOURCE_WITH_CLIENT_TYPE, ['cpus', protocol], errorMessage) if discoverDisks: try: vector.addAll(TTY_HR_Disk_Lib.disWinOS(hostOsh, shell)) except: errorMessage = 'Failed to discover disks' _logWarn( errorcodes. FAILED_DISCOVERING_RESOURCE_WITH_CLIENT_TYPE, ['disks', protocol], errorMessage) if discoverDrivers and shell.isWinOs(): try: vector.addAll( _discoverWindowsDeviceDriver(shell, hostOsh)) except: errorMessage = 'Failed to discover windows device driver by powershell' _logWarn( errorcodes. FAILED_DISCOVERING_RESOURCE_WITH_CLIENT_TYPE, ['windows device driver', protocol], errorMessage) if discoveriSCSIInfo: try: vector.addAll( TTY_HR_Disk_Lib.disWinOSiSCSIInfo(hostOsh, shell)) except: errorMessage = 'Failed to discover iSCSI info' _logWarn( errorcodes. FAILED_DISCOVERING_RESOURCE_WITH_CLIENT_TYPE, ['iSCSI', protocol], errorMessage) if discoverMemory: try: vector.addAll( TTY_HR_Memory_Lib.disWinOS(hostCmdbId, shell, Framework, langBund)) except: errorMessage = 'Failed to discover memory' _logWarn( errorcodes. FAILED_DISCOVERING_RESOURCE_WITH_CLIENT_TYPE, ['memory', protocol], errorMessage) processes = [] try: processesDiscoverer = process_discoverer.DiscovererByShellOnWindows( shell) processes = processesDiscoverer.discoverAllProcesses() if not processes: raise ValueError() except: errorMessage = 'Failed to discover processes' _logWarn( errorcodes. FAILED_DISCOVERING_RESOURCE_WITH_CLIENT_TYPE, ['processes', protocol], errorMessage) if processes: # save processes to DB process_discoverer.saveProcessesToProbeDb( processes, hostCmdbId, Framework) # report processes discoverProcesses = Boolean.parseBoolean( Framework.getParameter('discoverProcesses')) if discoverProcesses: processReporter = process.Reporter() for processObject in processes: processVector = processReporter.reportProcess( hostOsh, processObject) vector.addAll(processVector) if discoverUsers: try: vector.addAll(_discoverUsers(hostOsh, shell)) except: errorMessage = 'Failed to discover users' _logWarn( errorcodes. FAILED_DISCOVERING_RESOURCE_WITH_CLIENT_TYPE, ['users', protocol], errorMessage) cmdLineToInstalledSoftware = {} softNameToInstSoftOSH = {} if discoverSoftware: try: softwareOSHs = TTY_HR_Software_Lib.disWinOS( hostCmdbId, shell, Framework, langBund, softNameToInstSoftOSH) if softwareOSHs: vector.addAll(softwareOSHs) except: errorMessage = 'Failed to discover installed software' _logWarn(errorcodes.FAILED_DISCOVERING_RESOURCE, ['installed software', protocol], errorMessage) servicesByCmd = Hashtable() if discoverServices: try: srvcOSHs = NTCMD_HR_REG_Service_Lib.doService( shell, hostOsh, servicesByCmd, langBund, Framework) vector.addAll(srvcOSHs) except: errorMessage = 'Failed to discover services' _logWarn(errorcodes.FAILED_DISCOVERING_RESOURCE, ['services', protocol], errorMessage) connectivityEndPoints = [] try: tcpDiscoverer = Dis_TCP.getDiscovererByShell( client, Framework, shell) if tcpDiscoverer is not None: tcpDiscoverer.discoverTCP() connectivityEndPoints = tcpDiscoverer.getProcessEndPoints( ) except: errorMessage = 'Failed to run TCP discovery' _logWarn( errorcodes.FAILED_RUNNING_DISCOVERY_WITH_CLIENT_TYPE, ['tcp', protocol], errorMessage) appSign = applications.createApplicationSignature( Framework, client, shell) if processes: appSign.setProcessesManager( applications.ProcessesManager(processes, connectivityEndPoints)) servicesInfo = applications.ServicesInfo(servicesByCmd) appSign.setServicesInfo(servicesInfo) softwareInfo = applications.InstalledSoftwareInfo( cmdLineToInstalledSoftware, softNameToInstSoftOSH) appSign.setInstalledSoftwareInfo(softwareInfo) appSign.getApplicationsTopology(hostCmdbId) if discoverP2P: try: p2p = process_to_process.ProcessToProcess(Framework) p2p.getProcessesToProcess() except: errorMessage = 'Failed to run p2p discovery' _logWarn(errorcodes.FAILED_RUNNING_DISCOVERY, ['p2p', protocol], errorMessage) except JException, ex: exInfo = ex.getMessage() errormessages.resolveAndReport(exInfo, protocol, Framework) except:
def exportApplicationManifest(appName, customTaskProcessors={}): taskProcessors = {} taskProcessors.update(defaultTaskProcessors) taskProcessors.update(customTaskProcessors) prefs = Hashtable() appManagement = getJMXMBean1(type='AppManagement') manifest = ApplicationObject(appName, '../applications/%s.ear' % appName) deployment = getid1('/Deployment:%s/' % appName) appDeployment = deployment.deployedObject manifest.extras['startingWeight'] = '%d' % appDeployment.startingWeight manifest.extras['classLoadingMode'] = '%s' % appDeployment.classloader.mode webModuleClassLoadingModes = [] for module in appDeployment.modules: if module._type == 'WebModuleDeployment': webModuleClassLoadingModes.append( [module.uri, module.classloaderMode]) if webModuleClassLoadingModes: manifest.extras['webModuleClassLoadingMode'] = ( webModuleClassLoadingModes) scaMapping = {} try: for moduleInfo in [ l.split(':') for l in AdminTask.listSCAModules().splitlines() ]: scaMapping[moduleInfo[1]] = moduleInfo[0] except AttributeError: pass scaModuleName = scaMapping.get(appName) if scaModuleName: try: manifest.extras['scaModuleProperties'] = [ [scaModuleName] + l.split('=') for l in AdminTask.showSCAModuleProperties([ '-moduleName', scaModuleName, '-applicationName', appName ]).splitlines() ] except: pass try: scaImportWSBindings = [] deployedEndpointPat = re.compile(r'.*deployedEndpoint=([^,]+),.*') for importName in AdminTask.listSCAImports( ['-moduleName', scaModuleName, '-applicationName', appName]).splitlines(): try: importBinding = AdminTask.showSCAImportWSBinding([ '-moduleName', scaModuleName, '-applicationName', appName, '-import', importName ]) deployedEndpointMat = ( deployedEndpointPat.match(importBinding)) if deployedEndpointMat: scaImportWSBindings.append([ scaModuleName, importName, deployedEndpointMat.group(1) ]) except: pass if scaImportWSBindings: manifest.extras['scaImportWSBindings'] = scaImportWSBindings except: pass applicationWSPolicySetAttachments = wdr.task.adminTaskAsDictList( AdminTask.getPolicySetAttachments( ['-applicationName', appName, '-attachmentType', 'application'])) if applicationWSPolicySetAttachments: applicationWSPolicySetAttachmentList = [] for att in applicationWSPolicySetAttachments: applicationWSPolicySetAttachmentList.append( [att['name'], att['pattern.0'], att.get('binding', '')]) manifest.extras['applicationWSPolicySetAttachments'] = ( applicationWSPolicySetAttachmentList) clientWSPolicySetAttachments = wdr.task.adminTaskAsDictList( AdminTask.getPolicySetAttachments( ['-applicationName', appName, '-attachmentType', 'client'])) if clientWSPolicySetAttachments: clientWSPolicySetAttachmentList = [] for att in clientWSPolicySetAttachments: bindingName = att.get('binding', '') policyType = '' attributes = '' if bindingName != '': policyTypeList = AdminTask.listPolicyTypes([ '-bindingLocation', [['application', appName], ['attachmentId', att['id']]], '-attachmentType', 'client' ]).splitlines() if policyTypeList: policyType = policyTypeList[0] attributes = AdminTask.getBinding([ '-policyType', policyType, '-bindingLocation', [['application', appName], ['attachmentId', att['id']]], '-bindingName', bindingName, '-attachmentType', 'client' ]) clientWSPolicySetAttachmentList.append([ att['name'], att['pattern.0'], bindingName, policyType, attributes ]) manifest.extras['clientWSPolicySetAttachments'] = ( clientWSPolicySetAttachmentList) providerPolicySharingInfo = wdr.task.adminTaskAsDictList( AdminTask.getProviderPolicySharingInfo(['-applicationName', appName])) if providerPolicySharingInfo: providerPolicySharingInfoList = [] for psi in providerPolicySharingInfo: providerPolicySharingInfoList.append([ psi['resource'], psi['sharePolicyMethods'], psi.get('wsMexPolicySetName', ''), psi.get('wsMexPolicySetBinding', '') ]) manifest.extras['providerPolicySharingInfo'] = ( providerPolicySharingInfoList) for task in appManagement.getApplicationInfo(appName, prefs, None): taskProcessor = taskProcessors.get(task.name) if taskProcessor: taskProcessor['function'](Task(task), manifest, taskProcessor.get('columns')) for n in manifest.options.keys(): v = manifest.options[n] if isinstance(v, ListType): v.sort() for n in manifest.extras.keys(): v = manifest.extras[n] if isinstance(v, ListType): v.sort() return manifest
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()