def intialize():
        global domainProps;
        global userConfigFile;
        global userKeyFile;

        # test arguments
        if len(sys.argv) != 3:
                print 'Usage:  stopDomain.sh  <default.properties_file> <property_file>';
                exit();

				
		print 'Starting the initialization process';                                                                                                                                                    

    	try:
    		domainProps = Properties()

		# load DEFAULT properties                                                                                                                                                                               
		input = FileInputStream(sys.argv[1])
		domainProps.load(input)
		input.close()
			
		
		# load properties and overwrite defaults
		input = FileInputStream(sys.argv[2])
		domainProps.load(input)
		input.close()

                userConfigFile = File(sys.argv[2]).getParent()+'/'+domainProps.getProperty('domainName')+'.userconfig'
                userKeyFile = File(sys.argv[2]).getParent()+'/'+domainProps.getProperty('domainName')+'.userkey'

        except:
                print 'Cannot load properties  !';
                exit();

        print 'Initialization completed';
    def process(self):
        '''Read the XML file and map xpath items to metadata
        Return a list with 1 JsonSimple object (at most)
        '''
        jsonList = []
        data = None
        reader = None
        inStream = None
        document = None

        # Run the XML through our parser
        try:
            inStream = FileInputStream(File(self.file))
            reader = InputStreamReader(inStream, "UTF-8")
            document = self.saxReader.read(reader)
        # Parse fails
        except:
            raise
        # Close our file access objects
        finally:
            if reader is not None:
                reader.close()
            if inStream is not None:
                inStream.close()

        # Now go looking for all our data
        data = self.getNewJsonObject()
        self.__mapXpathToFields(document, self.map, data)

        if data is None:
            return None

        jsonList.append(JsonSimple(data))
        return jsonList
Exemple #3
0
    def process(self):
        '''Read the XML file and map xpath items to metadata
        Return a list with 1 JsonSimple object (at most)
        '''
        jsonList = []
        data = None
        reader = None
        inStream = None
        document = None
        
        # Run the XML through our parser
        try:
            inStream = FileInputStream(File(self.file))
            reader = InputStreamReader(inStream, "UTF-8")
            document = self.saxReader.read(reader)
        # Parse fails
        except:
            raise
        # Close our file access objects
        finally:
            if reader is not None:
                reader.close()
            if inStream is not None:
                inStream.close()

        # Now go looking for all our data
        data = self.getNewJsonObject()
        self.__mapXpathToFields(document, self.map, data)
        
        if data is None:
            return None
        
        jsonList.append(JsonSimple(data))
        return jsonList
    def process(self):
        #We'll return a list with 1 JsonSimple object
        jsonList = []
        data = None
        reader = None
        inStream = None
        document = None
        
        # Run the XML through our parser
        try:
            inStream = FileInputStream(File(self.file))
            reader = InputStreamReader(inStream, "UTF-8")
            document = self.saxReader.read(reader)
        # Parse fails
        except:
            raise
        # Close our file access objects
        finally:
            if reader is not None:
                reader.close()
            if inStream is not None:
                inStream.close()

        # Now go looking for all our data
        data = JsonObject()
        data.put("workflow_source", "XML Alert") # Default
        self.__mapXpathToFields(document, self.map, data)
        
        if data is None:
            return None
        
        jsonList.append(JsonSimple(data))
        return jsonList
def load_properties(property_file, exception_type=None):
    """
    Load the key=value properties file into a Properties object
    and then store the properties in a dictionary.
    :param property_file: Name of the property file to read
    :param exception_type: Throw the indicated tool exception
    :raise Tool exception if exception type included, or IOException if None
    :return: property dictionary
    """
    _method_name = 'load_properties'
    prop_dict = dict()
    props = Properties()
    input_stream = None
    try:
        input_stream = FileInputStream(property_file)
        props.load(input_stream)
        input_stream.close()
    except IOException, ioe:
        if input_stream is not None:
            input_stream.close()
        if exception_type is None:
            raise ioe
        ex = exception_helper.create_exception(exception_type,
                                               'WLSDPLY-01721',
                                               property_file,
                                               ioe.getLocalizedMessage(),
                                               error=ioe)
        __logger.throwing(ex, class_name=_class_name, method_name=_method_name)
        raise ex
def addPropertiesFromFile(props, filename, site_home):
    addProps = Properties()
    input = FileInputStream(filename)
    addProps.load(input)
    input.close()

    baseFileList = addProps.getProperty('base')
    
    if not baseFileList is None:
        baseFiles = baseFileList.split(",")
        for baseFile in baseFiles:
            baseFileResolved=getBaseFile(baseFile, site_home)
            if baseFileResolved=='':
                log.error('Configuration inherits from properties file that does not exist: ' + baseFile)
                log.info('Suggested Fix: Update the base property within ' + filename + ' to the correct file path')
                sys.exit()
            log.debug('Attempting to load properties from ' + baseFile)
            addPropertiesFromFile(addProps, baseFileResolved, site_home)
            addProps.remove('base')

    enum = addProps.keys()
    while enum.hasMoreElements():
        key = enum.nextElement()
        if props.getProperty(key) is None:
            props.setProperty(key, addProps.getProperty(key))
            addDataLinage(key,filename,addProps.getProperty(key))
Exemple #7
0
class report_generation:
  'Test Report Generation'

  def transformReport(self,stylesheet,xml,output,params):
    from java.io import FileInputStream
    from java.io import FileOutputStream
    from java.io import ByteArrayOutputStream

    from javax.xml.transform import TransformerFactory
    from javax.xml.transform.stream import StreamSource
    from javax.xml.transform.stream import StreamResult

    self.xsl   = FileInputStream("%s" % stylesheet)
    self.xml   = FileInputStream("%s" % xml)
    self.html  = FileOutputStream("%s" % output)

    try:
      self.xslSource   = StreamSource(self.xsl)
      self.tfactory    = TransformerFactory.newInstance()
      self.xslTemplate = self.tfactory.newTemplates(self.xslSource)
      self.transformer = self.xslTemplate.newTransformer()

      self.source = StreamSource(self.xml)
      self.result = StreamResult(self.html)

      for self.key,self.value in params.items():
        self.transformer.setParameter(self.key, self.value)

      self.transformer.transform(self.source, self.result)

    finally:
      self.xsl.close()
      self.xml.close()
      self.html.close()
Exemple #8
0
 def read_versions(self):
     versionsProperties = Properties()
     fin = FileInputStream(self.versionsFileName)
     versionsProperties.load(fin)
     scriptVersion = versionsProperties.getProperty("script")
     toolsVersion = versionsProperties.getProperty("tools")
     fin.close()
     return scriptVersion, toolsVersion
def load_redback_registry():
    reg = Properties()
    reg_file = 'redback.properties'
    if os.path.isfile(reg_file):
        reg_fd = FileInputStream(reg_file)
        reg.load(reg_fd)
        reg_fd.close()
    return reg
def load_redback_registry():
    reg = Properties()
    reg_file = 'redback.properties'
    if os.path.isfile(reg_file):
        reg_fd = FileInputStream(reg_file)
        reg.load(reg_fd)
        reg_fd.close()
    return reg
def loadProperties(fileName):
	properties = Properties()
	input = FileInputStream(fileName)
	properties.load(input)
	input.close()
	result= {}
	for entry in properties.entrySet(): result[entry.key] = entry.value
	return result
Exemple #12
0
def load_global_registry():
    reg = Properties()
    reg_file = 'global_platform.properties'
    if os.path.isfile(reg_file):
        reg_fd = FileInputStream(reg_file)
        reg.load(reg_fd)
        reg_fd.close()
    return reg
Exemple #13
0
 def read_versions(self):
     versionsProperties = Properties()
     fin = FileInputStream(self.versionsFileName)
     versionsProperties.load(fin)
     scriptVersion = versionsProperties.getProperty("script")
     toolsVersion = versionsProperties.getProperty("tools")
     fin.close()
     return scriptVersion, toolsVersion
Exemple #14
0
def getPushProperties():
    pushProperties          = HashMap()
    pushPropertiesFileStr   = "%s%s%s" % (adapterConfigBaseDir, FILE_SEPARATOR, PUSH_PROPERTIES_FILE)
    properties              = Properties()
    debugMode               = 0
    sortCSVFields           = ""
    smartUpdateIgnoreFields = ""
    testConnNameSpace       = "BMC.CORE"
    testConnClass           = "BMC_ComputerSystem"
    try:
        logger.debug("Checking push properties file for debugMode [%s]" % pushPropertiesFileStr)
        fileInputStream = FileInputStream(pushPropertiesFileStr)
        properties.load(fileInputStream)

        # Property: debugMode
        try:
            debugModeStr    = properties.getProperty("debugMode")
            if isNoneOrEmpty(debugModeStr) or string.lower(string.strip(debugModeStr)) == 'false':
                debugMode   = 0
            elif string.lower(string.strip(debugModeStr)) == 'true':
                debugMode   = 1
        except:
            logger.debugException("Unable to read debugMode property from push.properties")

        if debugMode:
            logger.debug("Debug mode = TRUE. XML data pushed to Remedy/Atrium will be persisted in the directory: %s" % adapterResBaseDir)
        else:
            logger.debug("Debug mode = FALSE")

        # Property: smartUpdateIgnoreFields
        try:
            smartUpdateIgnoreFields = properties.getProperty("smartUpdateIgnoreFields")
        except:
            logger.debugException("Unable to read smartUpdateIgnoreFields property from push.properties")

        # Property: sortCSVFields
        try:
            sortCSVFields = properties.getProperty("sortCSVFields")
        except:
            logger.debugException("Unable to read sortCSVFields property from push.properties")

        # Property: testConnNameSpace
        try:
            testConnNameSpace = properties.getProperty("testConnNameSpace")
        except:
            logger.debugException("Unable to read testConnNameSpace property from push.properties")

        # Property: testConnClass
        try:
            testConnClass = properties.getProperty("testConnClass")
        except:
            logger.debugException("Unable to read testConnClass property from push.properties")

        fileInputStream.close()
    except:
        logger.debugException("Unable to process %s file." % PUSH_PROPERTIES_FILE)

    return debugMode, smartUpdateIgnoreFields, sortCSVFields, testConnNameSpace, testConnClass
def intialize():
        global domainLocation;
        global jvmLocation;
        global domainTemplate;
        global domainProps;
        global adminUserName;
        global adminPassword;
        global userConfigFile;
        global userKeyFile;

        # test arguments
        if len(sys.argv) != 6:
                print 'Usage:  createDomain.sh <template-file> <default.properties_file> <property_file> <wls_username> <wls_password>';
                exit();

        print 'Starting the initialization process';

        domainTemplate = sys.argv[1];
        print 'Using Domain Template: ' + domainTemplate;
        try:
                domainProps = Properties()

                # load DEFAULT properties
                # print 'Reading default properties from '+sys.argv[2];
                input = FileInputStream(sys.argv[2])
                domainProps.load(input)
                input.close()


                # load properties and overwrite defaults
                input = FileInputStream(sys.argv[3])
                domainProps.load(input)
                input.close()

                adminUserName = sys.argv[4];
                adminPassword = sys.argv[5];

		# Files for generating secret key

		userConfigFile = File(sys.argv[3]).getParent()+'/'+domainProps.getProperty('domainName')+'.userconfig'
                print userConfigFile
		userKeyFile = File(sys.argv[3]).getParent()+'/'+domainProps.getProperty('domainName')+'.userkey'
	        print userKeyFile			

                domainLocation = domainProps.getProperty('domainsDirectory') + pathSeparator + domainProps.getProperty('domainName');
                print 'Domain Location: ' + domainLocation;
                if len(domainProps.getProperty('jvmLocation')) == 0:
                        print 'JVM location property not defined - cancel creation !';
                        exit();
                print 'JVM Location: ' + domainProps.getProperty('jvmLocation');

        except:
                dumpStack()
                print 'Cannot initialize creation process !';
                exit();

        print 'Initialization completed';
def loadMyProperties(fileName):
    properties = Properties()
    input = FileInputStream(fileName)
    properties.load(input)
    input.close()
    result = {}
    for entry in properties.entrySet():
        result[entry.key] = entry.value
    return result
Exemple #17
0
 def readBinaryFile(cls, rootFile):
     """ generated source for method readBinaryFile """
     in_ = FileInputStream(rootFile)
     out = ByteArrayOutputStream()
     #  Transfer bytes from in to out
     buf = [None]*1024
     while in_.read(buf) > 0:
         out.write(buf)
     in_.close()
     return out.toByteArray()
Exemple #18
0
def build_velocity_context(template_file):
    inputs = VelocityContext()
    fInputs = None
    try:
        fInputs = FileInputStream(template_file)
        Velocity.evaluate(inputs, StringWriter(), "inputs", fInputs)
        return inputs
    finally:
        if fInputs:
            fInputs.close()
Exemple #19
0
def read_tools_list(tmpToolsListFile):
    """Read the tools names and tools data urls
       from the downlaoded tools list
    """
    properties = Properties()
    fin = FileInputStream(tmpToolsListFile)
    properties.load(fin)
    toolsRefs = properties.getProperty("tools.list").split("|")
    fin.close()
    return toolsRefs
Exemple #20
0
def read_tools_list(tmpToolsListFile):
    """Read the tools names and tools data urls
       from the downlaoded tools list
    """
    properties = Properties()
    fin = FileInputStream(tmpToolsListFile)
    properties.load(fin)
    toolsRefs = properties.getProperty("tools.list").split("|")
    fin.close()
    return toolsRefs
def loadPropertiesFromFile(filename,props):
    newprops=Properties()
    inputstr = FileInputStream(filename)
    newprops.load(inputstr)
    inputstr.close()
    enum = newprops.keys()
    while enum.hasMoreElements():
        key = enum.nextElement()
        if props.getProperty(key) is None:
            props.setProperty(key, newprops.getProperty(key))
    return props
Exemple #22
0
def render(context, logString, template):
    sWriter = StringWriter()
    fIS = None
    try:
        sWriter.append(MSGTEMPLATE_PREFIX)
        fIS = FileInputStream(File(MSGTEMPLATE_DIR, template))
        Velocity.evaluate(context, sWriter, logString, fIS)
        sWriter.append(MSGTEMPLATE_SUFFIX)
        return sWriter.toString()
    finally:
        if fIS:
            fIS.close()
Exemple #23
0
    def test_read_file(self):
        from java.io import FileInputStream
        from java.lang import String

        filename = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                                'data/read_file.txt')
        fin = FileInputStream(filename)
        ar = jarray(20, JBYTE_ID)
        count = fin.read(ar)
        fin.close()
        s = String(ar, 0, count)
        self.assertEqual(str(s).strip(), 'aewrv3v')
Exemple #24
0
def descryptPropsFile(filepath):
	print
	print '----- Decrypting %s -----' % filepath
	try:
		properties = Properties()
		file = FileInputStream(filepath)
		properties.load(file)
		file.close()
		for entry in properties.entrySet():
			print '%s = %s' % (entry.key.strip(), java.lang.String(decrypt(entry.value.strip())))
	except IOError:
		print "Error: Unable to read file '%s' - check file permissions" % filepath
		print
Exemple #25
0
 def addFile(self, file, parentDirName=None):
   buffer = jarray.zeros(self._bufsize, 'b')
   inputStream = FileInputStream(file)
   jarEntryName = file.getName()
   if parentDirName:
     jarEntryName = parentDirName + "/" + jarEntryName
   self.getJarOutputStream().putNextEntry(JarEntry(jarEntryName))
   read = inputStream.read(buffer)
   while read <> -1:
       self.getJarOutputStream().write(buffer, 0, read)
       read = inputStream.read(buffer)
   self.getJarOutputStream().closeEntry()
   inputStream.close()
Exemple #26
0
    def __get_cert_from_p12(self, file, password=None):
        ks = KeyStore.getInstance("PKCS12")
        io = FileInputStream(file)
        if password is None:
            ks.load(io, None)
        else:
            ks.load(io, String(password).toCharArray())
        io.close()

        for alias in ks.aliases():
            if ks.isKeyEntry(alias):
                return ks.getCertificate(alias)
        return None
Exemple #27
0
    def test_read_file(self):
        from java.io import FileInputStream
        from java.lang import String

        filename = os.path.join(
            os.path.abspath(os.path.dirname(__file__)),
            'data/read_file.txt')
        fin = FileInputStream(filename)
        ar = jarray(20, JBYTE_ID)
        count = fin.read(ar)
        fin.close()
        s = String(ar, 0, count)
        self.assertEqual(str(s).strip(), 'aewrv3v')
def run():
    versionFile = File(os.getcwd(), 'core/resources/version.properties')
    log.debug('Checking if ' + str(versionFile) + ' exists')
    if os.path.exists(str(versionFile)):
        versionProperties = Properties()
        input = FileInputStream(versionFile)
        versionProperties.load(input)
        input.close()
        versionInfo=getVersionInfo(versionProperties)
    else:
    	versionInfo=getVersionInfo(None)
    log.info('this')
    log.info(versionInfo)
Exemple #29
0
 def addFile(self, file, parentDirName=None):
     buffer = jarray.zeros(self._bufsize, 'b')
     inputStream = FileInputStream(file)
     jarEntryName = file.getName()
     if parentDirName:
         jarEntryName = parentDirName + "/" + jarEntryName
     self.getJarOutputStream().putNextEntry(JarEntry(jarEntryName))
     read = inputStream.read(buffer)
     while read <> -1:
         self.getJarOutputStream().write(buffer, 0, read)
         read = inputStream.read(buffer)
     self.getJarOutputStream().closeEntry()
     inputStream.close()
def run():
    versionFile = File(os.getcwd(), 'core/resources/version.properties')
    log.debug('Checking if ' + str(versionFile) + ' exists')
    if os.path.exists(str(versionFile)):
        versionProperties = Properties()
        input = FileInputStream(versionFile)
        versionProperties.load(input)
        input.close()
        versionInfo = getVersionInfo(versionProperties)
    else:
        versionInfo = getVersionInfo(None)
    log.info('this')
    log.info(versionInfo)
Exemple #31
0
def read_tools_list(tmpToolsListFile):
    """Read the tools names and tools data urls
       from the downlaoded tools list
    """
    toolsInfo = []
    properties = Properties()
    fin = FileInputStream(tmpToolsListFile)
    properties.load(fin)
    toolsRefs = properties.getProperty("tools.list").split("|")
    for toolRef in toolsRefs:
        jarUrl = properties.getProperty(toolRef)
        toolsInfo.append([toolRef, jarUrl.replace("\n", "")])
    fin.close()
    return toolsInfo
Exemple #32
0
def copyclass(jc, fromdir, todir):
    import jar
    from java.io import FileInputStream, FileOutputStream

    name = apply(os.path.join, jc.split('.'))+'.class'
    fromname = os.path.join(fromdir, name)
    toname = os.path.join(todir, name)
    tohead = os.path.split(toname)[0]
    if not os.path.exists(tohead):
        os.makedirs(tohead)
    istream = FileInputStream(fromname)
    ostream = FileOutputStream(toname)
    jar.copy(istream, ostream)
    istream.close()
    ostream.close()
Exemple #33
0
def copyclass(jc, fromdir, todir):
    import jar
    from java.io import FileInputStream, FileOutputStream

    name = apply(os.path.join, jc.split('.')) + '.class'
    fromname = os.path.join(fromdir, name)
    toname = os.path.join(todir, name)
    tohead = os.path.split(toname)[0]
    if not os.path.exists(tohead):
        os.makedirs(tohead)
    istream = FileInputStream(fromname)
    ostream = FileOutputStream(toname)
    jar.copy(istream, ostream)
    istream.close()
    ostream.close()
Exemple #34
0
def compareFileHashes(dxFileName, amFileName, msgId):
    dxFile = FileInputStream(dxFileName)
    dxMsgContentHash = sha.new(str(dxFile.read()))
    dxFile.close()
    amFile = FileInputStream(amFileName)
    amMsgContentHash = sha.new(str(amFile.read()))
    amFile.close()

    if dxMsgContentHash.digest() == amMsgContentHash.digest():
        #print "message has same hash on AM partition and DX", msgId
        printQueue.append("output message " +  str(msgId) + " is present in DX")
        return True
    else:
        printErrorToRemigrate(msgId, " content hash differ on AM partition and DX. dx hash: " + dxMsgContentHash.hexdigest() + " am hash: " + amMsgContentHash.hexdigest())
        return False
Exemple #35
0
def load_property_file(filename):

    propfile = Properties()

    try:
        fin = FileInputStream(filename)
        propfile.load(fin)
        fin.close()
        return propfile
    except FileNotFoundException:
        LogError("File Not Found" + filename)
        sys.exit(1)
    except:
        LogError("Could not open Properties File" + filename)
        sys.exit(1)
 def login(self, domain, userid, password):
     fis = None
     userinfo = getResource(__file__, "users_db", userid + ".properties")
     if not os.path.exists(userinfo):
         raise UnauthorizedException("login", userid, userid)
     props = Properties()
     try:
         fis = FileInputStream(File(userinfo))
         props.load(fis)
     finally:
         fis.close()
     DumbIdentityManager.login(self, domain, userid, password)
     user = SimpleUser(userid, props)
     if user.getPassword() != password:
         raise UnauthorizedException("login", userid, userid)
     self.current = user
    def __get_manifest(self, source_path, from_archive):
        """
        Returns the manifest object for the specified path.
        The source path may be a jar, or an exploded path.
        :param source_path: the source path to be checked
        :param from_archive: if True, use the manifest from the archive, otherwise from the file system
        :return: the manifest, or None if it is not present
        :raises: IOException: if there are problems reading an existing manifest
        """
        manifest = None
        if string_utils.is_empty(source_path):
            return manifest

        source_path = self.model_context.replace_token_string(source_path)

        if from_archive and deployer_utils.is_path_into_archive(source_path):
            return self.archive_helper.get_manifest(source_path)

        else:
            if not os.path.isabs(source_path):
                # if this was in archive, it has been expanded under domain home.
                # or it may be a relative file intentionally placed under domain home.
                source_file = File(File(self.model_context.get_domain_home()), source_path)
            else:
                source_file = File(source_path)

            if source_file.isDirectory():
                # read the manifest directly from the file system
                manifest_file = File(source_file, MANIFEST_NAME)
                if manifest_file.exists():
                    stream = None
                    try:
                        stream = FileInputStream(manifest_file)
                        manifest = Manifest(stream)
                    finally:
                        if stream is not None:
                            try:
                                stream.close()
                            except IOException:
                                # nothing to report
                                pass
            else:
                # read the manifest from the deployable ear/jar/war on the file system
                archive = JarFile(source_file.getAbsolutePath())
                manifest = archive.getManifest()

        return manifest
Exemple #38
0
def intialize():
    global props

    if len(sys.argv) != 2:
        print 'Usage:  domain.py  <property_file>'
        exit()
    try:
        props = Properties()
        input = FileInputStream(sys.argv[1])
        props.load(input)
        input.close()
    except:

        print 'Cannot load properties  !'
        exit()

    print 'initialization completed'
Exemple #39
0
def intialize():
	global props
	
	if len(sys.argv) != 2:
		print 'Usage:  domain.py  <property_file>';
		exit();
	try:
		props = Properties()
		input = FileInputStream(sys.argv[1])
		props.load(input)
		input.close()
	except:

		print 'Cannot load properties  !';
		exit();
	
	print 'initialization completed';
Exemple #40
0
def intialize():
    global domainProps
    global userConfigFile
    global userKeyFile
    global overwrittenServerURL
    global levelToPrint

    # test arguments
    if ((len(sys.argv) != 4) and (len(sys.argv) != 5)):
        print 'Usage:  printStatusInformation.sh  <default.properties_file> <property_file> <SUMMARY / ALL>'
        print 'OR'
        print 'Usage:  printStatusInformation.sh  <default.properties_file> <property_file> <SUMMARY / ALL> <ADMIN-URL overwrite>'
        exit()

    print 'Starting the initialization process'

    try:
        domainProps = Properties()

        # load DEFAULT properties
        input = FileInputStream(sys.argv[1])
        domainProps.load(input)
        input.close()

        # load properties and overwrite defaults
        input = FileInputStream(sys.argv[2])
        domainProps.load(input)
        input.close()

        userConfigFile = File(sys.argv[2]).getParent(
        ) + '/' + domainProps.getProperty('domainName') + '.userconfig'
        userKeyFile = File(sys.argv[2]).getParent(
        ) + '/' + domainProps.getProperty('domainName') + '.userkey'

        levelToPrint = sys.argv[3]

        if (len(sys.argv) == 5):
            overwrittenServerURL = sys.argv[4]

    except:
        dumpStack()
        print 'Cannot load properties  !'
        exit()

    print 'Initialization completed'
Exemple #41
0
def deserialize(filepath):
  f = None
  o = None
  obj = None
  try:
    f = FileInputStream(filepath)
    o = ObjectInputStream(f)
    obj = o.readObject()
  except:
    syncPrintQ(sys.exc_info())
  finally:
    if f:
      f.close()
    if o:
      o.close()
  if obj is None:
    syncPrintQ("Failed to deserialize object at " + filepath)
  return obj
 def registerIcons(self):
     folder = os.path.join(self.folder,"icons")
     for image in os.listdir(folder):
         name,ext = os.path.splitext(image)
         if ext == ".png":
             name = name.lower()
             if not self.nameChecker.match(name):
                 continue
             stream = FileInputStream(os.path.join(folder,image))
             icon = self.api.getMarkerIcon("landmark_"+name)
             if icon is None:
                 icon = self.api.createMarkerIcon("landmark_"+name,name.capitalize(),stream)
             else:
                 icon.setMarkerIconImage(stream)
             stream.close()
             icon.setMarkerIconLabel(name)
             self.icons[name] = icon
     info("Loaded %s icons"%len(Landmarks.icons))
Exemple #43
0
def main(argv=None):
  if argv is None:
    argv = sys.argv

  if len(argv) < 2:
    print "Usage: ./configure-submodule.py submodule [submodule2 ...]"
    return 1

  # extract module dependencies using Fake
  fake = Fake()
  fakefile = ijPath + "/Fakefile"
  fis = FileInputStream(fakefile)
  parser = fake.parse(fis, File(ijPath))
  parser.parseRules([])
  fis.close()

  # process each submodule specified
  for arg in argv[1:]:
    processSubModule(arg, parser)
Exemple #44
0
    def __init__(self):
        dataDir = Settings.dataDir + 'WorkingWithWorksheets/RemovingWorksheetsusingSheetIndex/'

        fstream = FileInputStream(dataDir + "Book1.xls")

        #Instantiating a Workbook object with the stream
        workbook = Workbook(fstream)

        #Removing a worksheet using its sheet index
        workbook.getWorksheets().removeAt(0)

        #Saving the Excel file
        workbook.save(dataDir + "book.out.xls")

        #Closing the file stream to free all resources
        fstream.close()

        #Print Message
        print "Sheet removed successfully."
def add_folder(zos, folder_name, base_folder_name):
    f = File(folder_name)
    if not f.exists():
        return
    if f.isDirectory():
        for f2 in f.listFiles():
            add_folder(zos, f2.absolutePath, base_folder_name)
        return
    entry_name = folder_name[len(base_folder_name) + 1:len(folder_name)]
    ze = ZipEntry(entry_name)
    zos.putNextEntry(ze)
    input_stream = FileInputStream(folder_name)
    buffer = zeros(1024, 'b')
    rlen = input_stream.read(buffer)
    while (rlen > 0):
        zos.write(buffer, 0, rlen)
        rlen = input_stream.read(buffer)
    input_stream.close()
    zos.closeEntry()
Exemple #46
0
def add_folder(zos, folder_name, base_folder_name):
    f = File(folder_name)
    if not f.exists():
        return
    if f.isDirectory():
        for f2 in f.listFiles():
            add_folder(zos, f2.absolutePath, base_folder_name)
        return
    entry_name = folder_name[len(base_folder_name) + 1:len(folder_name)]
    ze = ZipEntry(entry_name)
    zos.putNextEntry(ze)
    input_stream = FileInputStream(folder_name)
    buffer = zeros(1024, 'b')
    rlen = input_stream.read(buffer)
    while (rlen > 0):
        zos.write(buffer, 0, rlen)
        rlen = input_stream.read(buffer)
    input_stream.close()
    zos.closeEntry()
def intialize():
        global domainProps;
        global userConfigFile;
        global userKeyFile;
        global overwrittenServerURL;
        global levelToPrint;

        # test arguments
        if ((len(sys.argv) != 3) and (len(sys.argv) != 4)):
                print 'Usage:  threaddump.py <default.properties_file> <property_file>';
                print 'OR'
                print 'Usage:  threaddump.py <default.properties_file> <property_file> <ADMIN-URL overwrite>';
                exit();


        print 'Starting the initialization process';

        try:
                domainProps = Properties()

                # load DEFAULT properties
                input = FileInputStream(sys.argv[1])
                domainProps.load(input)
                input.close()

                # load properties and overwrite defaults
                input = FileInputStream(sys.argv[2])
                domainProps.load(input)
                input.close()

                userConfigFile = File(sys.argv[2]).getParent()+'/'+domainProps.getProperty('domainName')+'.userconfig'
                userKeyFile = File(sys.argv[2]).getParent()+'/'+domainProps.getProperty('domainName')+'.userkey'

                if (len(sys.argv) == 4):
                    overwrittenServerURL = sys.argv[3];


        except:
                dumpStack()
                print 'Cannot load properties  !';
                exit();

        print 'Initialization completed';
Exemple #48
0
 def readScalarDataFile(self, scalarfile):
     scalarData = []
     for j in range(2):
         scalerData.append(range(9))
     fis = FileInputStream(self.scalarList[i])
     dis = DataInputStream(fis)
     scalerBytes = jarray.zeros(18 * 4, 'b')
     dis.read(scalerBytes, 0, 18 * 4)
     fis.close()
     offset = 0
     for j in range(2):
         for l in range(0, 36, 4):
             scalarData[j][
                 l / 4] = (0x000000FF & scalerBytes[offset + l + 0]) + (
                     (0x000000FF & scalerBytes[offset + l + 1]) << 8
                 ) + ((0x000000FF & scalerBytes[offset + l + 2]) << 16) + (
                     (0x000000FF & scalerBytes[offset + l + 3]) << 24)
         offset = offset + 36
     fis.close()
     return scalarData
    def __init__(self):
        dataDir = Settings.dataDir + 'WorkingWithWorksheets/RemovingWorksheetsusingSheetName/'
          
        #Creating a file stream containing the Excel file to be opened
        fstream = FileInputStream(dataDir + "Book1.xls");

        #Instantiating a Workbook object with the stream
        workbook = Workbook(fstream);

        #Removing a worksheet using its sheet name
        workbook.getWorksheets().removeAt("Sheet1");

        #Saving the Excel file
        workbook.save(dataDir + "book.out.xls");

        #Closing the file stream to free all resources
        fstream.close();

        #Print Message
        print "Sheet removed successfully.";
    def __init__(self):
        dataDir = Settings.dataDir + 'quickstart/'

        # Open the stream. Read only access is enough for Aspose.Words to load a document.
        stream = FileInputStream(dataDir + 'Document.doc')

        # Load the entire document into memory.
        doc = Document(stream)

        # You can close the stream now, it is no longer needed because the document is in memory.
        stream.close()

        # ... do something with the document
        # Convert the document to a different format and save to stream.
        dstStream = ByteArrayOutputStream()
        doc.save(dstStream, SaveFormat.RTF)
        output = FileOutputStream(dataDir + "Document Out.rtf")
        output.write(dstStream.toByteArray())
        output.close()

        print "Document loaded from stream and then saved successfully."
    def __init__(self):
        dataDir = Settings.dataDir + 'quickstart/'
        
        # Open the stream. Read only access is enough for Aspose.Words to load a document.
        stream = FileInputStream(dataDir + 'Document.doc')
        
        # Load the entire document into memory.
        doc = Document(stream)
        
        # You can close the stream now, it is no longer needed because the document is in memory.
        stream.close()
        
        # ... do something with the document
        # Convert the document to a different format and save to stream.
        dstStream = ByteArrayOutputStream()
        doc.save(dstStream, SaveFormat.RTF)
        output = FileOutputStream(dataDir + "Document Out.rtf")
        output.write(dstStream.toByteArray())
        output.close()

        print "Document loaded from stream and then saved successfully."
Exemple #52
0
def dom_document_from_file(f):
    if hasattr(f, 'name'):
        documentURI = os.path.abspath(f.name)
    else:
        documentURI = None
    bytestring = f.read()

    temp = File.createTempFile('someprefix', 'tmp')

    outputstream = FileOutputStream(temp)
    try:
        outputstream.write(bytestring)
    finally:
        outputstream.close()

    inputstream = FileInputStream(temp)
    try:
        dom_doc = dom_document_from_inputstream(inputstream)
        dom_doc.setDocumentURI(documentURI)
        return dom_doc
    finally:
        inputstream.close()
Exemple #53
0
def dom_document_from_file(f):
    if hasattr(f, 'name'):
        documentURI = os.path.abspath(f.name)
    else:
        documentURI = None
    bytestring = f.read()

    temp = File.createTempFile('someprefix', 'tmp')

    outputstream = FileOutputStream(temp)
    try:
        outputstream.write(bytestring)
    finally:
        outputstream.close()

    inputstream = FileInputStream(temp)
    try:
        dom_doc = dom_document_from_inputstream(inputstream)
        dom_doc.setDocumentURI(documentURI)
        return dom_doc
    finally:
        inputstream.close()
def getDebugMode():
    pushPropertiesFileStr = "%s%s%s" % (adapterConfigBaseDir, FILE_SEPARATOR, PUSH_PROPERTIES_FILE)
    properties = Properties()
    debugMode = 0
    try:
        logger.debug("Checking push properties file for debugMode [%s]" % pushPropertiesFileStr)
        fileInputStream = FileInputStream(pushPropertiesFileStr)
        properties.load(fileInputStream)
        debugModeStr = properties.getProperty("debugMode")
        if isNoneOrEmpty(debugModeStr) or string.lower(string.strip(debugModeStr)) == 'false':
            debugMode = 0
        elif string.lower(string.strip(debugModeStr)) == 'true':
            debugMode = 1
        fileInputStream.close()
    except:
        debugMode = 0 # ignore and continue with debugMode=0
        logger.debugException("Unable to process %s file." % PUSH_PROPERTIES_FILE)
    if debugMode:
        logger.debug("Debug mode = TRUE. XML data pushed to CA CMDB will be persisted in the directory: %s" % adapterResBaseDir)
    else:
        logger.debug("Debug mode = FALSE")
    return debugMode
def load_variables(file_path):
    """
    Load a dictionary of variables from the specified file.
    :param file_path: the file from which to load properties
    :return the dictionary of variables
    :raises VariableException if an I/O error occurs while loading the variables from the file
    """
    method_name = "load_variables"

    variable_map = {}
    props = Properties()
    input_stream = None
    try:
        input_stream = FileInputStream(file_path)
        props.load(input_stream)
        input_stream.close()
    except IOException, ioe:
        ex = exception_helper.create_variable_exception(
            'WLSDPLY-01730', file_path, ioe.getLocalizedMessage(), error=ioe)
        _logger.throwing(ex, class_name=_class_name, method_name=method_name)
        if input_stream is not None:
            input_stream.close()
        raise ex
Exemple #56
0
def iconv(file):
	print 'Converting', file
	f = File(file)
	if not f.exists():
		print file, 'does not exist'
		sys.exit(1)
	buffer = ByteBuffer.allocate(f.length() * 2)
	input = FileInputStream(f)
	input.getChannel().read(buffer)
	buffer.limit(buffer.position())
	buffer.position(0)
	if buffer.limit() != f.length():
		print file, 'could not be read completely'
		sys.exit(1)
	input.close()
	buffer = encoder.encode(decoder.decode(buffer))
	buffer.position(0)
	output = FileOutputStream(file + '.cnv')
	if output.getChannel().write(buffer) != buffer.limit():
		print file, 'could not be reencoded'
		sys.exit(1)
	output.close()
	f.delete()
	File(file + '.cnv').renameTo(f)
def __readBytes(file):
	# Returns the contents of the file in a byte array.
	inputstream = FileInputStream(file)
    
	# Get the size of the file
	length = file.length()

	# Create the byte array to hold the data
	bytes = jarray.zeros(length, "b")

	# Read in the bytes
	offset = 0
	numRead = 1
        while (offset < length) and (numRead > 0):
		numRead = inputstream.read(bytes, offset, len(bytes) - offset)
		offset += numRead

	# Ensure all the bytes have been read in
	if offset < len(bytes):
		log.warn("Could not read entire contents of '" + file.getName()) 

	# Close the input stream and return bytes
	inputstream.close()
	return bytes