示例#1
0
def monitorDomains():
    print 'starting the script for ', adminServerAddress, '....'
    username = adminUser
    password = adminPassword
    url = adminServerAddress 
    try:
        connect(username,password,url)
        
        domainRuntime()
        serverNames = domainRuntimeService.getServerRuntimes() 
        domainName = cmo.getName()
        print 'Getting data from domain ' , domainName
        fileToWrite = scriptHome + "/" + domainName + "/" + monitorDomain
        w = open(fileToWrite,"a")
        for s in serverNames:
            socketsOpenedTotalCount = s.getSocketsOpenedTotalCount()
            heap_details(s.getName())
            thread_details(s.getName())
            # Assign performance data
            
            # write monitor data for this instance jvm to monitorDomain
            timeStamping = Date()
            timeToShow = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT).format(timeStamping);
             
            infoLineMonitorData = domainName + "," + timeToShow + "," + s.getName() + "," + str(hfree) + "," + str(hsize)+ "," + str(hpercent) + "," + str(utime) + "," + str(socketsOpenedTotalCount) + "," + str(completedRequestCount) + "," + str(executeThreadIdleCount) + "," + str(executeThreadTotalCount) + "," + str(hoggingThreadCount) + "," + str(pendingUserRequestCount) + "," + str(queueLength) + "," + str(standbyThreadCount) + "," + str(throughput) +"\n"
            w.write(infoLineMonitorData) 
                     
        w.close()
        
        disconnect()
    except Exception, e:
        disconnect()
示例#2
0
def parse_argument( operator, argument, argument_type, field ):
  # Handle the degenerate cases where we don't know what type of field we're
  # looking at (this happens, say, in the context of a deref operation). We'll
  # just try our best to convert the argument based on what the parser tells us
  # to do.
  
  if field == None and argument_type == QueryParserTokenTypes.INT_VALUE:
    return int(argument)

  if field == None and argument_type == QueryParserTokenTypes.DECIMAL_VALUE:
    return float(argument)

  if field == None and argument_type == QueryParserTokenTypes.STRING_VALUE:
    return dequote(argument)

  # Now we'll handle the normal cases where we know what kind of DBField we're
  # dealing with. This gives much more precise results.
  
  field_type = field.getType()

  # Length operations get special treatment, since they take integer arguments
  # regardless of the type of the underlying DBField
  if operator in ["len<", "len<=", "len>", "len>=", "len=="] and \
     field.isArray() and \
     argument_type == QueryParserTokenTypes.INT_VALUE:
    return int(argument)

  if field_type == FieldType.NUMERIC and \
     argument_type == QueryParserTokenTypes.INT_VALUE:
    return int(argument)

  if field_type == FieldType.FLOAT and \
      argument_type == QueryParserTokenTypes.DECIMAL_VALUE:
    return float(argument)

  if field_type == FieldType.BOOLEAN:
    if argument_type == QueryParserTokenTypes.BOOLEAN_VALUE:
      if argument == "true":
        return Boolean.TRUE
      else:
        return Boolean.FALSE

    if argument_type == QueryParserTokenTypes.STRING_VALUE:
      return (int(dequote(argument)) != 0)
    if argument_type == QueryParserTokenTypes.INT_VALUE:
      return (int(argument) != 0)

  if field_type in [FieldType.STRING, FieldType.INVID, FieldType.IP] and \
     argument_type == QueryParserTokenTypes.STRING_VALUE:
    return dequote(argument)

  if field_type == FieldType.DATE and \
     argument_type == QueryParserTokenTypes.STRING_VALUE:
    return DateFormat.parse(dequote(argument))

  raise ParseException( "The field " + field.getName() + " takes arguments of type " + field.getTypeDesc() )
 def cronTest(self):
     self.logger.info("cronTest")
     dateFormat = DateFormat.getDateInstance(DateFormat.SHORT,
                                             Locale.GERMAN)
     assert CronExpression("* * * ? * SAT,SUN *").isSatisfiedBy(
         dateFormat.parse("29.07.2017"))
     assert CronExpression("* * * ? * SAT,SUN *").isSatisfiedBy(
         dateFormat.parse("30.07.2017"))
     assert CronExpression("* * * ? * SAT,SUN *").isSatisfiedBy(
         dateFormat.parse("03.09.2017"))
示例#4
0
 def __init__( self, data, headings ) :
     info = []
     df   = DateFormat.getDateInstance( DateFormat.SHORT )
     for date, size, path in data :
         info.append(
             [
                 df.parse( date ),
                 Integer( size.strip().replace( ',', '' ) ),
                 String( path )
             ]
         )
     DefaultTableModel.__init__( self, info, headings )
示例#5
0
 def __init__(self, data, headings):
     info = []
     df = DateFormat.getDateInstance(DateFormat.SHORT)
     for tf, date, size, f, d in data:
         info.append([
             Boolean(tf == '1'),
             df.parse(date),
             Integer(size.strip().replace(',', '')),
             Float(f),
             Double(d)
         ])
     DefaultTableModel.__init__(self, info, headings)
示例#6
0
def getExpirationDate(license_props):
    """
    Iterates through a property list and returns the expirationDate
    """
    if license_props:
        df = DateFormat.getInstance()
        for p in license_props:
            if p.getKey() == "expirationDate":
                val = p.getValue()
                if val.getClass().getName() == "java.util.GregorianCalendar":
                    return df.format(val.getTime())
    return None
示例#7
0
def printHostHardwareSummary(si):
    host = InventoryNavigator(si.getRootFolder()).searchManagedEntities("HostSystem")
    df = DateFormat.getInstance()
    for h in host:
        hinfo = h.getHardware()
        print "Hypervisor Name: " + h.getName()
        print hinfo.getSystemInfo().getVendor(),
        print hinfo.getSystemInfo().getModel()
        print "Bios: ", hinfo.getBiosInfo().getBiosVersion(),
        print df.format(hinfo.getBiosInfo().getReleaseDate().getTime())
        print "Overall Status: ", 
        print h.getOverallStatus().toString().capitalize()
        print "CPU Info: ", hinfo.getCpuPkg()[0].getDescription()
        print "\tCPU's: ", hinfo.getCpuInfo().getNumCpuPackages()
        print "\tCores: ", hinfo.getCpuInfo().getNumCpuCores()
        print "Memory Info: %.2f GB" % (hinfo.getMemorySize() * pow(10.0, -9))
    def getDailyScheduleName(self):
        self.scheduleName = None
        now = Date()
        for calendarItem in self.config:
            self.logger.info("Parser: found calendar item: " +
                             str(calendarItem))
            # check if daily schedule exists:
            try:
                self.schedules.getSchedules(calendarItem['daily_schedule'])
            except Exception as e:
                self.logger.warn("Config Error" + str(e))
                raise e

            if calendarItem.get('cron') != None:
                cronExpression = "* * * " + calendarItem.get('cron')
                self.logger.debug(cronExpression)
                self.logger.debug(now)
                if CronExpression(cronExpression).isSatisfiedBy(now):
                    # don't break we want to test the config
                    if self.scheduleName == None:
                        self.scheduleName = calendarItem['daily_schedule']
            else:  # has to be timerange
                df = DateFormat.getDateInstance(DateFormat.SHORT,
                                                Locale.GERMAN)
                fromDate = df.parse(calendarItem['timerange']['from'])
                toDate = df.parse(calendarItem['timerange']['to'])
                self.logger.debug(calendarItem['timerange']['from'])
                self.logger.debug(fromDate)
                self.logger.debug(calendarItem['timerange']['to'])
                self.logger.debug(toDate)
                self.logger.debug(now)
                if now.before(toDate) and now.after(fromDate):
                    # don't break we want to test the config
                    if self.scheduleName == None:
                        self.scheduleName = calendarItem['daily_schedule']

        if self.scheduleName == None:
            self.logger.warn("Todays daily schedule: " +
                             str(self.scheduleName))
        else:
            self.logger.info("todays daily schedule: " +
                             str(self.scheduleName))
        return self.scheduleName
示例#9
0
def dumpPropertyList(pList):
    """
    Iterates through a property list and prints the key/value pairs
    Primarily for debugging
    """
    FORMAT = "%16s %s"
    for p in pList:
        k = p.getKey()
        if p.getValue().__class__ is unicode or \
                p.getValue().__class__ is long:
            v = p.getValue()

        elif p.getValue().getClass().getName() == "com.vmware.vim25.KeyValue":
            v = p.getValue().getValue()
        elif p.getValue().getClass().getName() == "java.util.GregorianCalendar":
            df = DateFormat.getInstance()
            v = df.format(p.getValue().getTime())
        else:
            v = "Val: UNABLE TO PRINT; " + p.getValue().getClass().getName()

        print FORMAT % (k.capitalize()+":", v)
示例#10
0
def setColumnWidths(table):
    #---------------------------------------------------------------------------
    # It's possible for this table to not have a header...
    #---------------------------------------------------------------------------
    header = table.getTableHeader()
    if header:
        hRenderer = header.getDefaultRenderer()
    else:
        hRenderer = None

    #---------------------------------------------------------------------------
    # Variables used to access the table properties and data
    #---------------------------------------------------------------------------
    tcm = table.getColumnModel()  # Table Column Model
    data = table.getModel()  # To access table data
    margin = tcm.getColumnMargin()  # gap between columns

    #---------------------------------------------------------------------------
    # For each column, determine the maximum width required
    #---------------------------------------------------------------------------
    rows = data.getRowCount()  # Number of rows
    cols = tcm.getColumnCount()  # Number of cols

    #---------------------------------------------------------------------------
    # Used for parse & format date strings & objects
    #---------------------------------------------------------------------------
    df = DateFormat.getDateInstance(DateFormat.MEDIUM)

    tWidth = 0  # Table width
    for i in range(cols):  # For col 0..N
        col = tcm.getColumn(i)  # TableColumn: col i
        idx = col.getModelIndex()  # model index: col i

        #-----------------------------------------------------------------------
        # To determine the preferred column width, we
        # must use the current renderer for this column
        #-----------------------------------------------------------------------
        render = col.getHeaderRenderer()  # header renderer,
        if not render:  #
            render = hRenderer  #   or a default

        #-----------------------------------------------------------------------
        # Get preferred header width for column i
        #-----------------------------------------------------------------------
        if render:
            comp = render.getTableCellRendererComponent(
                table, col.getHeaderValue(), 0, 0, -1, i)
            cWidth = comp.getPreferredSize().width
        else:
            cWidth = -1
        #-----------------------------------------------------------------------
        # Compute the maximum width required for the data values in this column
        #-----------------------------------------------------------------------
        Type = data.getColumnClass(i)  # dataType: col i
        for row in range(rows):
            v = data.getValueAt(row, idx)  # value
            if Type == Date:
                val = df.format(v)  # formatted date
                r = table.getDefaultRenderer(String)
            else:
                val = Type(v)
                r = table.getCellRenderer(row, i)
            comp = r.getTableCellRendererComponent(
                table,
                val,  # formatted value
                0,  # not selected
                0,  # not in focus
                row,  # row num
                i  # col num
            )
            cWidth = max(cWidth, comp.getPreferredSize().width)

        if cWidth > 0:
            col.setPreferredWidth(cWidth + margin)

        #-----------------------------------------------------------------------
        # Table width = sum of column widths
        #-----------------------------------------------------------------------
        tWidth += col.getPreferredWidth()

    #---------------------------------------------------------------------------
    # Set the preferred viewport size so we don't (initially) see scrollbars
    # Note: This assumes a uniform row height for every row
    #---------------------------------------------------------------------------
    table.setPreferredScrollableViewportSize(
        Dimension(tWidth, rows * table.getRowHeight()))
示例#11
0
 def put(self, item):
     self.lblLabel.setText(item.getCaption())
     v = item.getValue()
     if v in ("", None):
         v = DateFormat.getDateInstance(DateFormat.SHORT).format(Date())
     self.btnDo.setText(v)
示例#12
0
def getBasicInformation():
    print 'starting the script for ', adminServerAddress, '....'
    username = adminUser
    password = adminPassword
    url = adminServerAddress
    try:
        connect(username, password, url)
        binaryVersion = cmo.getConfigurationVersion()
        domainRuntime()
        serverNames = domainRuntimeService.getServerRuntimes()
        domainName = cmo.getName()
        print 'Getting data from domain ', domainName
        w = open(inventoryWLS, "a")
        for s in serverNames:
            cd("/ServerRuntimes/" + s.getName())
            serverName = cmo.getName()
            serverState = cmo.getState()
            activationTime = cmo.getActivationTime()
            currentDirectory = cmo.getCurrentDirectory()
            valueThisIsAdminServer = cmo.isAdminServer()
            if valueThisIsAdminServer:
                thisAdminServer = "true"
            else:
                thisAdminServer = "false"
            currentMachine = cmo.getCurrentMachine()
            listenAddress = cmo.getListenAddress()
            listenPort = cmo.getListenPort()
            socketsOpenedTotalCount = cmo.getSocketsOpenedTotalCount()
            cd("/ServerRuntimes/" + s.getName() + "/JVMRuntime/" + s.getName())
            javaVendor = cmo.getJavaVendor()
            javaJVMDescription = cmo.getType()
            javaVersion = cmo.getJavaVersion()
            if javaJVMDescription == "JRockitRuntime":
                numberOfProcessors = cmo.getNumberOfProcessors()
            else:
                numberOfProcessors = 0
            osJvmName = cmo.getOSName()
            osJvmVersion = cmo.getOSVersion()
            heapSizeMax = cmo.getHeapSizeMax()

            # write inventory data for this instance jvm
            timeStamping = Date()
            timeToShow = DateFormat.getDateTimeInstance(
                DateFormat.SHORT, DateFormat.SHORT).format(timeStamping)

            infoLineForServerInstance = str(domainName) + "|" + str(
                timeToShow
            ) + "|" + str(serverName) + "|" + str(listenAddress) + "|" + str(
                listenPort
            ) + "|" + str(serverState) + "|" + str(binaryVersion) + "|" + str(
                currentDirectory) + "|" + str(thisAdminServer) + "|" + str(
                    currentMachine) + "|" + str(activationTime) + "|" + str(
                        socketsOpenedTotalCount
                    ) + "|" + str(javaVendor) + "|" + str(
                        javaJVMDescription
                    ) + "|" + str(javaVersion) + "|" + str(
                        osJvmName) + "|" + str(osJvmVersion) + "|" + str(
                            numberOfProcessors) + "|" + str(heapSizeMax) + "\n"
            infoServerToWrite = infoLineForServerInstance
            w.write(infoServerToWrite)

        w.close()
        # Now, get applications deployed on Domain in specific directory
        dir = scriptHome + "/" + domainName
        if not os.path.exists(dir):
            os.makedirs(dir)
        feApp = open(dir + "/" + appsDomainInv, "a")
        domainConfig()

        dsCounter = 0
        allJDBCResources = cmo.getJDBCSystemResources()
        for jdbcResource in allJDBCResources:
            dsname = jdbcResource.getName()
            dsResource = jdbcResource.getJDBCResource()
            #        dsServer = dsResource.getJDBCDataSourceParams().getJNDINames()#[0]
            dsJNDIname = dsResource.getJDBCDataSourceParams().getJNDINames(
            )  #[0]
            dsInitialCap = dsResource.getJDBCConnectionPoolParams(
            ).getInitialCapacity()
            dsMaxCap = dsResource.getJDBCConnectionPoolParams().getMaxCapacity(
            )
            dsParams = dsResource.getJDBCDataSourceParams()
            dsDriver = dsResource.getJDBCDriverParams().getDriverName()
            conn = dsResource.getJDBCDriverParams().getUrl()
            test = dsResource.getJDBCDriverParams().getProperties()
            test1 = dsResource.getJDBCConnectionPoolParams()
            targets = jdbcResource.getTargets()
            user = ''
            readTimeOut = ''
            conTimeOut = ''
            streamAsBlob = ''
            print 'FOR'

            timeStamping = Date()
            timeToShow = DateFormat.getDateTimeInstance(
                DateFormat.SHORT, DateFormat.SHORT).format(timeStamping)

            infoLineForDBDetails = str(dsname) + "|" + str(
                dsResource) + "|" + str(dsJNDIname) + "|" + str(
                    dsParams) + "|" + str(dsDriver) + "|" + str(
                        conn) + "|" + str(test1) + "|" + str(targets) + "\n"
            print(infoLineForDBDetails)
            dbs = open(dir + "/" + dataSourcersDomainInv, "a")
            dbs.write(infoLineForDBDetails)
            dbs.close()

            dsCounter += 1
        try:
            user = get("/JDBCSystemResources/" + dsname + "/Resource/" +
                       dsname + "/JDBCDriverParams/" + dsname +
                       "/Properties/" + dsname + "/Properties/user/Value")
            readTimeOut = get("/JDBCSystemResources/" + dsname + "/Resource/" +
                              dsname + "/JDBCDriverParams/" + dsname +
                              "/Properties/" + dsname +
                              "/Properties/oracle.jdbc.ReadTimeout/Value")
            conTimeOut = get("/JDBCSystemResources/" + dsname + "/Resource/" +
                             dsname + "/JDBCDriverParams/" + dsname +
                             "/Properties/" + dsname +
                             "/Properties/oracle.net.CONNECT_TIMEOUT/Value")
            streamAsBlob = get("/JDBCSystemResources/" + dsname +
                               "/Resource/" + dsname + "/JDBCDriverParams/" +
                               dsname + "/Properties/" + dsname +
                               "/Properties/SendStreamAsBlob/Value")

        except Exception, e:
            fe = open(pathConnectionProblems, "a")
            errorLineToWrite = url + "," + username + "," + password + "," + str(
                e) + "\n"
            fe.write(errorLineToWrite)
            fe.close
        vasApps = cmo.getAppDeployments()
        for app in vasApps:
            appName = app.getName()
            targetAppToWrite = ""
            targetsApp = app.getTargets()
            for targetApp in targetsApp:
                targetAppToWrite = targetAppToWrite + "," + targetApp.getName()
            appDataLineToWrite = appName + targetAppToWrite + "\n"
            feApp.write(appDataLineToWrite)
        feApp.close()
        disconnect()
示例#13
0
import com.ibm.custom.WordHelper as WordHelper
import java.util.Calendar as Calendar
import java.text.DateFormat as DateFormat
import java.util.List as List
import java.util.Arrays as Arrays

df = DateFormat.getInstance()
rp = WordHelper("./samplet.dotx")  #Create Helper Object
doc = rp.getDocument()  #Sample method to get Document object

#Replace Keywords:
rp.replaceText("##LetterNum##", "123/456/789")
rp.replaceText("##CurrentDate##", df.format(Calendar.getInstance().getTime()))
rp.replaceText("##CustomerName##", "IBM")
rp.replaceText("##TicketID##", "ABC123")
rp.replaceText("##ResolveDate##", df.format(Calendar.getInstance().getTime()))
rp.replaceText("##SolutionDetails##", "Restart Server\n Recreate User\n")
rp.replaceText("##Resolver##", "John Doe")

#Update Tables - template table first row must match the header
tbheads = Arrays.asList("Circuit ID", "Speed", "Location")
tbdata = Arrays.asList(Arrays.asList("CI100", "100 Mbps", "Singapore"),
                       Arrays.asList("CI210", "1 Gbps", "Kuala Lumpur"),
                       Arrays.asList("CI320", "10 Gbps", "Bangkok"))
rp.updateTable(tbheads, tbdata)

#Save the result
rp.saveAs("./jython_output.doc")
示例#14
0
from java.util import Date
from java.util import Locale
from java.text import DateFormat
dateFormatter = DateFormat.getDateInstance(DateFormat.FULL, Locale.FRANCE);
today = Date()
print today
dateOut = dateFormatter.format(today);
print dateOut