Пример #1
0
  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()
Пример #2
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 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))
Пример #5
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 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
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
Пример #8
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
Пример #9
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()
Пример #10
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
Пример #12
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)
        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)
Пример #14
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()
Пример #15
0
	def write(self, name, file):
		fp = self.getFile(name)
		if isinstance(file, ByteArrayOutputStream):
			file.writeTo(fp)
		else:
			if isinstance(file, type('')):
				file = FileInputStream(file)
			data = jarray.zeros(1024*4, 'b')
			#print 'writing', file,
			while 1:
				n = file.read(data)
				#print n,
				if n == -1: break
				fp.write(data, 0, n)
Пример #16
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
Пример #17
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()
Пример #18
0
    def add_audio_frame(dataDir):

        dataDir = Settings.dataDir + 'WorkingWithShapes/Frame/'

        # Create an instance of Presentation class
        pres = Presentation()

        # Get the first slide
        sId = pres.getSlides().get_Item(0)

        # Load the wav sound file to stram
        fstr = FileInputStream(File(dataDir + "Bass-Drum.wav"))

        # Add Audio Frame
        af = sId.getShapes().addAudioFrameEmbedded(50, 150, 100, 100, fstr)

        # Set Play Mode and Volume of the Audio
        audioPlayModePreset = AudioPlayModePreset
        audioVolumeMode = AudioVolumeMode
        af.setPlayMode(audioPlayModePreset.Auto)
        af.setVolume(audioVolumeMode.Loud)

        # Write the presentation as a PPTX file
        save_format = SaveFormat
        pres.save(dataDir + "AudioFrameEmbed.pptx", save_format.Pptx)

        print "Added audio frame to slide, please check the output file."
Пример #19
0
    def add_picture_frame(dataDir):

        dataDir = Settings.dataDir + 'WorkingWithShapes/Frame/'

        # Create an instance of Presentation class
        pres = Presentation()

        # Get the first slide
        sId = pres.getSlides().get_Item(0)

        # Instantiate the Image class
        imgx = pres.getImages().addImage(
            FileInputStream(File(dataDir + "aspose-logo.jpg")))

        # Add Picture Frame with height and width equivalent of Picture
        shapeType = ShapeType
        sId.getShapes().addPictureFrame(shapeType.Rectangle, 50, 150,
                                        imgx.getWidth(), imgx.getHeight(),
                                        imgx)

        # Write the presentation as a PPTX file
        save_format = SaveFormat
        pres.save(dataDir + "RectPicFrame.pptx", save_format.Pptx)

        print "Added picture frame to slide, please check the output file."
Пример #20
0
def obtenerListaDataSources(mainParams):
    propInputStream = FileInputStream("02_datasources.properties")
    dsProps = Properties()
    dsProps.load(propInputStream)
    totalDs = int(dsProps.get("ds.total"))
    print '>> totalDs : ' + str(totalDs)
    listaDs = []
    i = 1
    while (i <= totalDs):
        recurso = {}
        recurso['dominio'] = mainParams['dominio']
        recurso['name'] = dsProps.get("ds.%s.name" %(str(i)))
        recurso['jndi'] = dsProps.get("ds.%s.jndiname" %(str(i)))
        recurso['drvr'] = dsProps.get("ds.%s.driver.class" %(str(i)))
        recurso['url'] = dsProps.get("ds.%s.url" %(str(i)))
        recurso['user'] = dsProps.get("ds.%s.username" %(str(i)))
        recurso['pswd'] = dsProps.get("ds.%s.password" %(str(i)))
        recurso['iniCap'] = dsProps.get("ds.%s.initialCapacity" %(str(i)))
        recurso['maxCap'] = dsProps.get("ds.%s.maxCapacity" %(str(i)))
        recurso['timeOut'] = dsProps.get("ds.%s.connection.reserved.timeout" %(str(i)))
        recurso['testQry'] = dsProps.get("ds.%s.test.query" %(str(i)))
        recurso['gblTrPr'] = dsProps.get("ds.%s.global.transaction.protocol" %(str(i)))
        recurso['type'] = mainParams['type']
        recurso['target'] = mainParams['target']
        recurso['shrink'] = None
        listaDs.append(recurso)
        print '>> [%s] item' %(str(i))
        i = i + 1
    
    return listaDs
def main():
    propInputStream = FileInputStream(sys.argv[1])
    configProps = Properties()
    configProps.load(propInputStream)

    adminUrl = configProps.get("adminUrl")
    importUser = configProps.get("importUser")
    importPassword = configProps.get("importPassword")
    csvLoc = configProps.get("csvLoc")
    #log = configProps.get("log")

    connect(importUser, importPassword, adminUrl)
    edit()
    startEdit()

    #date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    #file = open(csvLoc)

    expClasspath(csvLoc)
    expArgument(csvLoc)

    print('\n')

    activate()
    disconnect()
Пример #22
0
def createAppRolesAndGroups():
	try:
		propInputStream = FileInputStream("createAppRoles.properties")
		#inputStreamReader = InputStreamReader(propInputStream,"UTF8")		
		configProps = Properties()
		configProps.load(inputStreamReader)		

		appRoleTotal = configProps.get("approle.total")
		i=0

		while (i < int(appRoleTotal)) :
			
			roleName, groupName = configProps.get("approle.name.group."+ str(i)).split('.')
			
			print '|-----------Role Name: ' + roleName + ' Group Name: ' + groupName
			createGroup(groupName)
			createApplicationRole(roleName)
			grantApplicationRole(roleName,groupName)
			print '|-----------'
			i = i + 1

		
	except:
		print 'ERROR'
		print sys.exc_info()[0] 
		print sys.exc_info()[1]
		exit()
Пример #23
0
 def endElement(self, uri, lname, qname):
     if self.state == 1 and uri == "http://www.w3.org/2002/xforms" and lname == "model":
         #вставка биндов для правил в mainModel
         stream = FileInputStream(self.bindPath)
         self.parser.parse(InputSource(stream))
         self.state = 0
     self.xmlWriter.writeEndElement()
Пример #24
0
def mainproc():
    u'''Функция для склейки карточки с блоками правил'''
    try:
        rootPath = AppInfoSingleton.getAppInfo().getCurUserData().getPath(
        ) + '/xforms/'
    except:
        rootPath = 'E:/Projects/celesta/ssmmd/userscore/ssmmd/xforms/file/'

    templatePath = rootPath + add  #путь к карточке, в которую необходимо вставить праила
    rulePath = rootPath + 'ruleTemplate.xml'  #путь к блоку с правилами
    bindPath = rootPath + 'bindTemplate.xml'  #путь к блоку с биндами для правил

    stringWriter = StringWriter()
    xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(
        stringWriter)

    parser = XMLReaderFactory.createXMLReader()
    handler = XformsAddRules(rulePath, bindPath, xmlWriter)
    parser.setContentHandler(handler)
    parser.setErrorHandler(handler)
    parser.setFeature("http://xml.org/sax/features/namespace-prefixes", True)
    parser.setProperty("http://xml.org/sax/properties/lexical-handler",
                       handler)

    stream = FileInputStream(templatePath)
    parser.parse(InputSource(stream))
    xmlWriter.close()
    stringWriter.close()
    return unicode(stringWriter)
def main():
    propInputStream = FileInputStream(sys.argv[1])
    configProps = Properties()
    configProps.load(propInputStream)

    adminUrl = configProps.get("adminUrl")
    importUser = configProps.get("importUser")
    importPassword = configProps.get("importPassword")
    csvLoc = configProps.get("csvLoc")
    log = configProps.get("log")

    connect(importUser, importPassword, adminUrl)
    edit()
    startEdit()

    date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    file = open(csvLoc)
    out = open(log, 'a+')

    for line in file.readlines():
        if line.strip().startswith('add'):
            addClasspath(line, out, date)
        if line.strip().startswith('check'):
            checkClasspath(line, out, date)
        if line.strip().startswith('remove'):
            removeClasspath(line, out, date)
        else:
            continue

    print('\n')

    activate()
    disconnect()
def permissionsload(context,
                    main=None,
                    add=None,
                    filterinfo=None,
                    session=None,
                    elementId=None,
                    data=None):
    permissions = PermissionsCursor(context)
    roles = RolesCursor(context)
    rolesCustomPerms = rolesCustomPermsCursor(context)
    customPerms = customPermsCursor(context)
    customPermsTypes = customPermsTypesCursor(context)
    cursors = [
        roles, permissions, customPermsTypes, customPerms, rolesCustomPerms
    ]
    files = [
        'roles', 'permissions', 'customPermsTypes', 'customPerms',
        'rolesCustomPerms'
    ]

    for i in range(len(cursors)):
        filePath = os.path.join(
            os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
            files[i] + '.xml')
        # raise Exception(filePath)
        if add == 'upload':
            dataStream = FileOutputStream(filePath)
        elif add == 'download':
            dataStream = FileInputStream(filePath)
        exchange = DataBaseXMLExchange(dataStream, cursors[i])
        if add == 'upload':
            exchange.downloadXML()
        elif add == 'download':
            exchange.uploadXML()
        dataStream.close()
Пример #27
0
    def set_image_as_background_color(dataDir):

        dataDir = Settings.dataDir + 'WorkingWithSlidesInPresentation/Background/'

        # Instantiate Presentation class that represents the presentation file
        pres = Presentation()

        # Set the background with Image

        backgroundType = BackgroundType
        fillType = FillType
        pictureFillMode = PictureFillMode

        pres.getSlides().get_Item(0).getBackground().setType(
            backgroundType.OwnBackground)
        pres.getSlides().get_Item(
            0).getBackground().getFillFormat().setFillType(fillType.Picture)
        pres.getSlides().get_Item(0).getBackground().getFillFormat(
        ).getPictureFillFormat().setPictureFillMode(pictureFillMode.Stretch)

        # Set the picture
        imgx = pres.getImages().addImage(
            FileInputStream(File(dataDir + 'night.jpg')))

        # Image imgx = pres.getImages().addImage(image)
        # Add image to presentation's images collection

        pres.getSlides().get_Item(0).getBackground().getFillFormat(
        ).getPictureFillFormat().getPicture().setImage(imgx)

        # Saving the presentation
        save_format = SaveFormat
        pres.save(dataDir + "ContentBG_Image.pptx", save_format.Pptx)

        print "Set image as background, please check the output file."
def main():
  propInputStream = FileInputStream(sys.argv[1])
  configProps = Properties()
  configProps.load(propInputStream)
   
  url=configProps.get("adminUrl")
  username=configProps.get("importUser")
  password=configProps.get("importPassword")
  csvLoc=configProps.get("csvLoc")
  
  connect(username , password , url)
  edit()
  file=open(csvLoc)
  for line in file.readlines():
    if line.strip().startswith('module'):
      createJMSModule(line)
    elif line.strip().startswith('foreign'):
      createForeignServer(line)
    elif line.strip().startswith('dest'):
      createForeignDest(line)
    elif line.strip().startswith('conn'):
      createforeignConnFactName(line)
    else:
      continue
	
  disconnect()
Пример #29
0
def get_carl_marc_record(position):
    if os.name != 'java':
        return
    previous_value = 0
    marc_file = None
    for number in SORTED_POSITIONS:
        if previous_value <= position and number > position:
            if CARL_POSITIONS.has_key(number):
                marc_file = CARL_POSITIONS[number]
                break
        previous_value = number
    if marc_file is None:
        print("{0} not found in MARC records".format(position))
        return None


#        raise ValueError("{0} not found in MARC records".format(position))
    offset = position - CARL_STATS[marc_file].get('start')
    collection_file = FileInputStream(
        os.path.join(DATA_ROOT, "Coalliance-Catalog", marc_file))
    collection_reader = marc4j.MarcStreamReader(collection_file)
    counter = 0
    while collection_reader.hasNext():
        counter += 1
        record = collection_reader.next()
        if counter == offset:
            return record
Пример #30
0
    def fill_shapes_with_picture(dataDir):

        dataDir = Settings.dataDir + 'WorkingWithShapes/FillingShapes/'

        # Create an instance of Presentation class
        pres = Presentation()

        # Get the first slide
        sld = pres.getSlides().get_Item(0)

        # Add autoshape of rectangle type
        shapeType = ShapeType
        shp = sld.getShapes().addAutoShape(shapeType.Rectangle, 50, 150, 75,
                                           150)

        # Set the fill type to Picture
        fillType = FillType
        shp.getFillFormat().setFillType(fillType.Picture)

        # Set the picture fill mode
        pictureFillMode = PictureFillMode
        shp.getFillFormat().getPictureFillFormat().setPictureFillMode(
            pictureFillMode.Tile)

        # Set the picture
        imgx = pres.getImages().addImage(
            FileInputStream(File(dataDir + "night.jpg")))

        shp.getFillFormat().getPictureFillFormat().getPicture().setImage(imgx)

        # Write the presentation as a PPTX file
        save_format = SaveFormat
        pres.save(dataDir + "RectShpPic.pptx", save_format.Pptx)

        print "Filled shapes with Picture, please check the output file."
Пример #31
0
 def SetIcon(self,icon,size=None,top=False):
     from javafx.scene.control import ContentDisplay;
     if os.path.isfile(icon):
         iv = ImageView(Image(FileInputStream(icon)))
         if size: iv.setFitHeight(size); iv.setFitWidth(size)
         self.ctrl.setGraphic(iv)
         if top: self.ctrl.setContentDisplay(ContentDisplay.TOP)
Пример #32
0
	def actionPerformed(self,actionEvent):
		accl = self.linac_setup_controller.linac_wizard_document.getAccl()
		cav_name_node_dict = self.linac_setup_controller.getCavNameNodeDict(accl)
		fc = JFileChooser(constants_lib.const_path_dict["LINAC_WIZARD_FILES_DIR_PATH"])
		fc.setDialogTitle("Read Cavities Amp. and Phases from external file ...")
		fc.setApproveButtonText("Open")
		returnVal = fc.showOpenDialog(self.linac_setup_controller.linac_wizard_document.linac_wizard_window.frame)
		if(returnVal == JFileChooser.APPROVE_OPTION):
			fl_in = fc.getSelectedFile()
			file_name = fl_in.getName()
			buff_in = BufferedReader(InputStreamReader(FileInputStream(fl_in)))
			line = buff_in.readLine()
			while( line != null):
				#print "debug line=",line				
				res_arr = line.split()
				if(len(res_arr) == 3):
					cav_name = res_arr[0]
					amp = float(res_arr[1])
					phase = float(res_arr[2])
					if(cav_name_node_dict.has_key(cav_name)):
						#print "debug cav=",cav_name," amp=",amp," phase",phase						
						cav = cav_name_node_dict[cav_name]
						cav.setDfltCavAmp(amp)
						cav.setDfltCavPhase(phase)
				line = buff_in.readLine()
 def readConfig(self, fh=None, xml=None):
     self.fh = fh
     self.xml = xml
     self.tree = None
     self.doc = None
     self.cellTree = None
     if self.fh != None:
         self.logger.info("readConfig: processing xml file")
         self.logger.debug("readConfig: file %s " % fh)
         input = FileInputStream(self.fh)
         fhtree = builder.parse(input)
         self.tree = fhtree.getDocumentElement()
         self.cellTree = fhtree.getElementById('Cell')
     elif self.xml != None:
         self.logger.info("readConfig: processing xml String")
         str = StringReader(xml)
         strstrm = InputSource(str)
         self.doc = builder.parse(strstrm)
         self.tree = self.doc.getDocumentElement()
         self.cellTree = self.doc.getElementById('Cell')
     else:
         self.logger.error(
             "readConfig: You did not supply a valid xml file handle or xml string to the readConfig method."
         )
         raise ProcessConfigException(
             "readConfig: You did not supply a valid xml file handle or xml string to the readConfig method."
         )
     self.logger.debug("readConfig: self.tree = %s" % (self.tree))
     self.treeDict = []
     self.logger.debug("readConfig: processing base tree elements")
     self.logger.debug("readConfig: self.tree: %s " % self.tree)
     self.walkXMLTree(self.tree, 0)
     self.logger.debug("readConfig: self.treeDict = %s" % (self.treeDict))
     return self.treeDict
def initConfigToScriptRun():

    environment = sys.argv[1]

    loadProperties("properties/" + environment + "-weblogic.properties")

    global configProps
    propInputStream = FileInputStream("properties/" + environment +
                                      "-weblogic.properties")
    configProps = Properties()
    configProps.load(propInputStream)

    hideDisplay()
    hideDumpStack("false")
    try:
        if connectEncrypted == "true":
            connect(userConfigFile=configFile,
                    userKeyFile=keyFile,
                    url=adminUrl)

        else:
            connect(adminUser, adminPassword, adminUrl)
        domainRuntime()
    except WLSTException:
        print 'No server is running at ' + adminUrl
        stopExecution('You need to be connected.')
Пример #35
0
def persistNewProfileName(domainConfigurationDirectory, profileName):
    from oracle.fabric.profiles.impl import ProfileConstants;
    fileName = domainConfigurationDirectory + File.separatorChar + 'server-profile-mbean-config.xml'
    profileProperties = Properties()
    profileProperties.loadFromXML(FileInputStream(fileName))
    profileProperties.setProperty(ProfileConstants.CURRENT_SOA_PROFILE_PROPERTY_NAME, profileName)
    profileProperties.storeToXML(FileOutputStream(fileName), None)
    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
Пример #37
0
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';
Пример #38
0
    def write(self, archive, path, dest):
        archive.putArchiveEntry(ZipArchiveEntry(dest))

        input = BufferedInputStream(FileInputStream(path))

        IOUtils.copy(input, archive)
        input.close()
        archive.closeArchiveEntry()
def getDeployedVersion(serviceGroupName, serviceName, interfaceVersion, environmentName) :
    propInputStream = FileInputStream(os.environ["HOME"] + "/osb_deployed_versions.properties")
    configProps = Properties()
    configProps.load(propInputStream)
    result = configProps.get(serviceGroupName + "." + serviceName + "." + interfaceVersion + "." + environmentName)
    if result == None:
        return "N/A"
    return result
Пример #40
0
def readYaml(file):
    from java.io import FileInputStream
    from org.yaml.snakeyaml import Yaml

    input = FileInputStream(file)
    yaml = Yaml()
    data = yaml.load(input)
    return data
 def open(self):
     ScriptingUtils.log(ScriptingUtils.WARN,
                        "Loading file xml " + self.fname)
     self.resource = FileInputStream(File(self.fname))
     self.parser.setInput(self.resource, None)
     ScriptingUtils.log(ScriptingUtils.WARN, "File loaded.")
     self.initValues()
     self.readInitValues()
Пример #42
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';
Пример #43
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'
Пример #44
0
    def getSslContext(self) :
	keyStore = KeyStore.getInstance("PKCS12")
        pwdArray = [x for x in self.transportKeyStorePassword]
        trustPwdArray = [x for x in self.trustKeyStorePassword]
	keyStore.load( FileInputStream(self.transportKeyStore), pwdArray)
        
	sslContext = SSLContexts.custom().loadKeyMaterial(keyStore,   pwdArray).loadTrustMaterial( File(self.trustKeyStore), trustPwdArray).build()
	return sslContext	
Пример #45
0
def getDeployedVersionFromFile(mavenArtifactId, environmentName) :
    propInputStream = FileInputStream(os.environ["HOME"] + "/osb_deployed_versions.properties")
    configProps = Properties()
    configProps.load(propInputStream)
    result = configProps.get(mavenArtifactId + "." + environmentName)
    if result == None:
        return "N/A"
    return result
 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))
Пример #47
0
 def __get_key_from_p12(self, file, password=None):
     io = FileInputStream(file)
     pkcs12 = PKCS12(io)
     if password is not None:
         try:
             pkcs12.decrypt(String(password).toCharArray())
         except:
             raise ValueError("Invalid passphrase for .p12 certificate!")
     return pkcs12.getKey()
Пример #48
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
Пример #49
0
 def transform_into_stream(self, input, output):
     '''
     >>> T.transform('input.xml', sys.stdout)
     '''
     from java.io import FileInputStream
     inp_path = os.path.abspath(input)
     with closing(FileInputStream(inp_path)) as inp_fis:
         out_fos = wrap_filelike_outputstream(output)
         return self._transform(inp_fis, out_fos)
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()
Пример #51
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)
Пример #52
0
 def parseXMLfile(self,xmlfile):
   try:
     import sys, traceback
     from java.io import FileInputStream
     self.builder= self.createBlankDocument()
     self.input = FileInputStream(xmlfile)
     self.doc = self.builder.parse(self.input)
     self.input.close()
     return self.doc
   except:
     print "exception: %s" % traceback.format_exception(*sys.exc_info())
    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."
Пример #55
0
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';
Пример #56
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()
Пример #57
0
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
Пример #58
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
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