def replaceDocumentSummary(self, ole2filename, blank=False):
    fin = FileInputStream(ole2filename)
    fs = NPOIFSFileSystem(fin)
    root = fs.getRoot()
    si = False
    siFound = False
    for obj in root:
       x = obj.getShortDescription()
       if x == (u"\u0005" + "DocumentSummaryInformation"):   
          siFound=True
          if blank == False:
             test = root.getEntry((u"\u0005" + "DocumentSummaryInformation")) 
             dis = DocumentInputStream(test);
             ps = PropertySet(dis);
             try:
                si = DocumentSummaryInformation(ps)
             except UnexpectedPropertySetTypeException as e:
                sys.stderr.write("Error writing old DocumentSymmaryInformation:" + str(e).replace('org.apache.poi.hpsf.UnexpectedPropertySetTypeException:',''))
                sys.exit(1)
                
    if blank == False and siFound == True:
       si.write(root, (u"\u0005" + "DocumentSummaryInformation"))
    else:
       ps = PropertySetFactory.newDocumentSummaryInformation()      
       ps.write(root, (u"\u0005" + "DocumentSummaryInformation"));
    
    out = FileOutputStream(ole2filename);
    fs.writeFilesystem(out);
    out.close();
def extractZip(zip, dest):
    "extract zip archive to dest directory"
    
    logger.info("Begin extracting:" + zip + " --> " +dest)
    mkdir_p(dest)
    zipfile = ZipFile(zip)

    entries = zipfile.entries()
    while entries.hasMoreElements():
        entry = entries.nextElement()

        if entry.isDirectory():
            mkdir_p(os.path.join(dest, entry.name))
        else:
            newFile = File(dest, entry.name)
            mkdir_p(newFile.parent)
            zis = zipfile.getInputStream(entry)
            fos = FileOutputStream(newFile)
            nread = 0
            buffer = ByteBuffer.allocate(1024)
            while True:
                nread = zis.read(buffer.array(), 0, 1024)
                if nread <= 0:
                        break
                fos.write(buffer.array(), 0, nread)

            fos.close()
            zis.close()

    logger.info("End extracting:" + str(zip) + " --> " + str(dest))
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()
Exemple #4
0
def write_variables(program_name, variable_map, file_path, append=False):
    """
    Write the dictionary of variables to the specified file.
    :param program_name: name of tool that invoked the method which will be written to the variable properties file
    :param variable_map: the dictionary of variables
    :param file_path: the file to which to write the properties
    :param append: defaults to False. Append properties to the end of file
    :raises VariableException if an error occurs while storing the variables in the file
    """
    _method_name = 'write_variables'
    _logger.entering(program_name,
                     file_path,
                     append,
                     class_name=_class_name,
                     method_name=_method_name)
    props = Properties()
    for key in variable_map:
        value = variable_map[key]
        props.setProperty(key, value)

    comment = exception_helper.get_message('WLSDPLY-01731', program_name)
    output_stream = None
    try:
        output_stream = FileOutputStream(File(file_path), Boolean(append))
        props.store(output_stream, comment)
        output_stream.close()
    except IOException, ioe:
        ex = exception_helper.create_variable_exception(
            'WLSDPLY-20007', file_path, ioe.getLocalizedMessage(), error=ioe)
        _logger.throwing(ex, class_name=_class_name, method_name=_method_name)
        if output_stream is not None:
            output_stream.close()
        raise ex
Exemple #5
0
def unzip_atp_wallet(wallet_file, location):

    if not os.path.exists(location):
        os.mkdir(location)

    buffer = jarray.zeros(1024, "b")
    fis = FileInputStream(wallet_file)
    zis = ZipInputStream(fis)
    ze = zis.getNextEntry()
    while ze:
        fileName = ze.getName()
        newFile = File(location + File.separator + fileName)
        File(newFile.getParent()).mkdirs()
        fos = FileOutputStream(newFile)
        len = zis.read(buffer)
        while len > 0:
            fos.write(buffer, 0, len)
            len = zis.read(buffer)

        fos.close()
        zis.closeEntry()
        ze = zis.getNextEntry()
    zis.closeEntry()
    zis.close()
    fis.close()
 def actionPerformed(self,e=None):
   i18n = ToolsLocator.getI18nManager()
   panel = e.getSource()
   if not panel.isLabelingEnabled():
     return
   labeling = panel.getLabelingStrategy()
   if labeling == None:
     return
   layer = panel.getLayer()
   initialPath = None
   getFile = getattr(layer.getDataStore().getParameters(),"getFile",None)
   if getFile != None:
     initialPath=getFile().getParent()
   else:
     initialPath = ToolsUtilLocator.getFileDialogChooserManager().getLastPath("OPEN_LAYER_FILE_CHOOSER_ID", None)
   f = filechooser(
     OPEN_FILE,
     title=i18n.getTranslation("_Select_a_file_to_save_the_labeling"),
     initialPath=initialPath,
     multiselection=False,
     filter=("gvslab",)
   )
   if f==None :
     return
   trace("filename %s" % f)
   try:
     fos = FileOutputStream(f)
     persistenceManager = ToolsLocator.getPersistenceManager()
     persistenceManager.putObject(fos, labeling)
   finally:
     fos.close()
Exemple #7
0
def getMsgRaw(fileName, rs):
    msgID = rs.getLong(1)
    size = rs.getInt(2)
    storageLocation = StoredMessage.stripOldStorageDir(rs.getString(3))
    custID = rs.getInt(4)
    ts = rs.getTimestamp(5)
    receivedDate = None
    if ts is not None:
        receivedDate = Date(ts.getTime)
    msg = StoredMessage(custID, msgID, storageLocation, None, None, receivedDate, 0, 0, 0, 0, None, amPartId, size, size, None, None)

    if msg:
        # do some validation
        if long(msgId) != msg.getMessageId():
            printQueue.append("consumer: ERROR: message ID " + str(msgId) + " not the same as " + str(msg.getMessageId()))

        #print "found message", msgId, "in DB for AM partition"
        msgStream = msg.getEncryptedCompressedContentStream()
        if msgStream:
            out = FileOutputStream(fileName)
            FileUtils.copyStream(msg.getEncryptedCompressedContentStream(), out)
            out.flush()
            out.close()
            #print "found message", msgId, "on disk in AM partition"
            return True
        else:
            printErrorToRemigrate(msgId, " not found on disk for AM partition.")
            return False
    else:
        printErrorToRemigrate(msgId, " not found in db for AM partition.")
        return False
Exemple #8
0
def proc1(context):
    #result = lyraplayer.getInstance(context, main='''{"sessioncontext":{"sid":"admin","userdata":"default","phone":"","username":"******","fullusername":"******","urlparams":{"urlparam":{"@name":"patientId","@value":["56"]}},"email":"","login":"******","sessionid":"06635C092D9884D757C65CC9D21DCD10","related":{"xformsContext":{"formData":{"schema":{"data":{"@visitDate":"2015-05-22T17:49:04"},"hypotheses":{"@block":"0","hypothesis":{"@name":"\u0422\u0435\u0441\u0442\u043e\u0432\u0430\u044f \u0440\u0430\u0437\u0440\u0430\u0431\u043e\u0442\u043a\u0430 \u0441 \u0442\u0430\u0431\u043b\u0438\u0446\u0430\u043c\u0438","@id":"11"}},"@xmlns":""}},"partialUpdate":"false","@id":"inspectionCard"}},"ip":"127.0.0.1"}}''')
    #result = lyraplayer.getInstance(context, main='testgrain.testform.TestForm')
    result = lyraplayer.getFormInstance(context, 'testgrain.testform.TestForm')
    fos = FileOutputStream('c:/temp/debug.log')
    try:
        print result.findRec()

        print result.move(
            '=',
            '''<schema recversion="1" formId="testgrain.testform.TestForm">
    <ff1 type="INT" null="false" local="true">5</ff1>
    <ff2 type="INT" null="false" local="true">0</ff2>
    <id type="INT" null="false" local="false">2</id>
    <attrVarchar type="VARCHAR" null="false" local="false">e</attrVarchar>
    <attrInt type="INT" null="false" local="false">11</attrInt>
    <f1 type="BIT" null="false" local="false">true</f1>
    <f2 type="BIT" null="false" local="false">true</f2>
    <f4 type="REAL" null="false" local="false">4.0</f4>
    <f5 type="REAL" null="false" local="false">4.0</f5>
    <f6 type="VARCHAR" null="false" local="false">1</f6>
    <f7 type="VARCHAR" null="true" local="false"/>
    <f8 type="DATETIME" null="false" local="false">2015-11-04T19:25:54</f8>
    <f9 type="DATETIME" null="false" local="false">2015-11-20T19:25:56</f9>
</schema>
''')
        #result.serialize(fos)
    finally:
        fos.close()
    print 'done'
Exemple #9
0
    def extract_obj(self, file_path, res, offset):
        try:
            f = File(file_path)

            # check same name file.
            counter = 0
            while True:

                # The same file name is not exists.
                if not f.exists():
                    break

                # Count up the file name.
                counter += 1
                stem = u"".join(file_path.split(u".")[:-1])
                ex = file_path.split(u".")[-1]

                _file_path = u"{}({}).{}".format(stem, counter, ex)
                f = File(_file_path)

            fos = FileOutputStream(f)

            fos.write(res[offset:])
            self._stdout.printf("save as \"%s\".\n\n", f.getPath())

            fos.close()

        except Exception as e:
            self._stderr.println("[!] In extract_obj.")
            self._stderr.println(e)
   def replaceSummaryInfo(self, ole2filename, blank=False):

      fin = FileInputStream(ole2filename)
      fs = NPOIFSFileSystem(fin)
      root = fs.getRoot()
      si = False
      siFound = False
      for obj in root:
         x = obj.getShortDescription()
         if x == (u"\u0005" + "SummaryInformation"):
            siFound = True
            if blank == False:
               test = root.getEntry((u"\u0005" + "SummaryInformation")) 
               dis = DocumentInputStream(test);
               ps = PropertySet(dis);
               #https://poi.apache.org/apidocs/org/apache/poi/hpsf/SummaryInformation.html
               si = SummaryInformation(ps);

      if blank == False and siFound == True:
         si.write(root, (u"\u0005" + "SummaryInformation"))
      else:
         ps = PropertySetFactory.newSummaryInformation()      
         ps.write(root, (u"\u0005" + "SummaryInformation"));
      
      out = FileOutputStream(ole2filename);
      fs.writeFilesystem(out);
      out.close();
Exemple #11
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()
def retrieve_an_archive(cust_id, archive_name, user_id, chunk_hint, file_name, output_ids):
    print "\nretrieve_a_chunk routine:: output file_name is :", file_name

    try:
        outfile_stream = FileOutputStream(file_name)
    except:
        print "retrieve_a_chunk routine:: Failed to open output stream on file : ", file_name, "..returning"
        return None

    # retrieve data
    mc = ManagementContainer.getInstance()
    rm = mc.getRecoveryManager()

    l_cust_id = Integer.parseInt(cust_id);
    l_user_id = Integer.parseInt(user_id);
    sosw = IRecoveryManager.SimpleOutputStreamWrapper(outfile_stream)

    try:
        rm.createPerUserActiveRecoveryArchiveFile(l_cust_id, archive_name, l_user_id, sosw, chunk_hint)
    except:
        print "retrieve_a_chunk routine:: `Exception while creating active recovery archive..returning"
        sys.exc_info()[1].printStackTrace()

        print("*** print_exc:")
        traceback.print_exc(file=sys.stdout)
        outfile_stream.close()
        raise

    outfile_stream.close()
    return get_chunk_hint(file_name, output_ids)
Exemple #13
0
 def __getFile(self, packageDir, filename):
     file = File(packageDir, filename)
     if not file.exists():
         out = FileOutputStream(file)
         IOUtils.copy(Services.getClass().getResourceAsStream("/workflows/" + filename), out)
         out.close()
     return file
Exemple #14
0
class XmlWriter(AbstractXmlWriter):

    def __init__(self, path):
        self.path = path
        self._output = FileOutputStream(path)
        self._writer = SAXTransformerFactory.newInstance().newTransformerHandler()
        self._writer.setResult(StreamResult(self._output))
        self._writer.startDocument()
        self.content('\n')
        self.closed = False

    def start(self, name, attributes={}, newline=True):
        attrs = AttributesImpl()
        for attrname, attrvalue in attributes.items():
            attrs.addAttribute('', '', attrname, '', attrvalue)
        self._writer.startElement('', '', name, attrs)
        if newline:
            self.content('\n')

    def content(self, content):
        if content is not None:
            content = self._encode(content)
            self._writer.characters(content, 0, len(content))

    def end(self, name, newline=True):
        self._writer.endElement('', '', name)
        if newline:
            self.content('\n')

    def close(self):
        self._writer.endDocument()
        self._output.close()
        self.closed = True
def saveHM(filename):
    # Create new HTTP client
    client = HttpClient()
    client.getParams().setAuthenticationPreemptive(True)
    defaultcreds = UsernamePasswordCredentials(user, password)
    client.getState().setCredentials(AuthScope.ANY, defaultcreds)

    # Get data across HTTP
    url = (
        "http://"
        + host
        + ":"
        + str(port)
        + "/admin/savedataview.egi?type="
        + type
        + "&data_format=NEXUSHDF5_LZW_6&data_saveopen_action=OPEN_ONLY"
    )
    getMethod = GetMethod(url)
    getMethod.setDoAuthentication(True)
    client.executeMethod(getMethod)

    # Save locally
    file = File(directory + "/" + filename)
    out = FileOutputStream(file)
    out.write(getMethod.getResponseBody())
    out.close()

    # Clean up
    getMethod.releaseConnection()
Exemple #16
0
def exportAll(exportConfigFile, generalConfigFile):
    try:
        print "Loading export config from :", exportConfigFile
        exportConfigProp = loadProps(exportConfigFile,generalConfigFile)
        adminUrl = exportConfigProp.get("adminUrl")
        user = exportConfigProp.get("user")
        passwd = exportConfigProp.get("password")

        jarFileName = exportConfigProp.get("jarFileName")
        customFile = exportConfigProp.get("customizationFile")

        passphrase = exportConfigProp.get("passphrase")
        project = exportConfigProp.get("project")

        connectToServer(user, passwd, adminUrl)
        print 'connected'

        ALSBConfigurationMBean = findService("ALSBConfiguration", "com.bea.wli.sb.management.configuration.ALSBConfigurationMBean")
        print "ALSBConfiguration MBean found"

        print project
        if project == None :
            ref = Ref.DOMAIN
            collection = Collections.singleton(ref)
            if passphrase == None :
                print "Export the config"
                theBytes = ALSBConfigurationMBean.export(collection, true, None)
            else :
                print "Export and encrypt the config"
                theBytes = ALSBConfigurationMBean.export(collection, true, passphrase)
        else :
            ref = Ref.makeProjectRef(project);
            print "Export the project", project
            collection = Collections.singleton(ref)
            theBytes = ALSBConfigurationMBean.exportProjects(collection, passphrase)
        print 'fileName',jarFileName
        aFile = File(jarFileName)
        print 'file',aFile
        out = FileOutputStream(aFile)
        out.write(theBytes)
        out.close()
        print "ALSB Configuration file: "+ jarFileName + " has been exported"

        if customFile != None:
            print collection
            query = EnvValueQuery(None, Collections.singleton(EnvValueTypes.WORK_MANAGER), collection, false, None, false)
            customEnv = FindAndReplaceCustomization('Set the right Work Manager', query, 'Production System Work Manager')
            print 'EnvValueCustomization created'
            customList = ArrayList()
            customList.add(customEnv)
            print customList
            aFile = File(customFile)
            out = FileOutputStream(aFile)
            Customization.toXML(customList, out)
            out.close()

#        print "ALSB Dummy Customization file: "+ customFile + " has been created"
    except:
        raise
Exemple #17
0
 def save_config(self):
     """Save preferences to config file
     """
     out = FileOutputStream(app.configFileName)
     app.properties.store(out, None)
     out.close()
     #load new preferences
     self.config = ConfigLoader(self)
Exemple #18
0
 def save_versions(self):
     print "save versions"
     versionsProperties = Properties()
     outFile = FileOutputStream(self.versionsFileName)
     versionsProperties.setProperty("script", self.app.SCRIPTVERSION)
     versionsProperties.setProperty("tools", self.app.TOOLSVERSION)
     versionsProperties.store(outFile, None)
     outFile.close()
Exemple #19
0
 def save_config(self):
     """Save preferences to config file
     """
     out = FileOutputStream(app.configFileName)
     app.properties.store(out, None)
     out.close()
     #load new preferences
     self.config = ConfigLoader(self)
Exemple #20
0
 def save_versions(self):
     print "save versions"
     versionsProperties = Properties()
     outFile = FileOutputStream(self.versionsFileName)
     versionsProperties.setProperty("script", self.app.SCRIPTVERSION)
     versionsProperties.setProperty("tools", self.app.TOOLSVERSION)
     versionsProperties.store(outFile, None)
     outFile.close()
 def save_example(self, label, image_byte_array):
     output_file_name = label + "_" + str(java.lang.System.currentTimeMillis()) + ".png"
     save_path = File(self.dir_path, output_file_name).getCanonicalPath()
     fileos = FileOutputStream(save_path)
     for byte in image_byte_array:
         fileos.write(byte)
     fileos.flush()
     fileos.close()
Exemple #22
0
def _buildProjectJar(element, document):
    component = element.getRootElement().getComponent()

    larchJarURL = app_in_jar.getLarchJarURL()
    chosenJarURL = None
    if larchJarURL is None:
        openDialog = JFileChooser()
        openDialog.setFileFilter(
            FileNameExtensionFilter('Larch executable JAR (*.jar)', ['jar']))
        response = openDialog.showDialog(component, 'Choose Larch JAR')
        if response == JFileChooser.APPROVE_OPTION:
            sf = openDialog.getSelectedFile()
            if sf is not None:
                chosenJarURL = sf.toURI().toURL()
        else:
            return

    jarFile = None
    bFinished = False
    while not bFinished:
        saveDialog = JFileChooser()
        saveDialog.setFileFilter(
            FileNameExtensionFilter('JAR file (*.jar)', ['jar']))
        response = saveDialog.showSaveDialog(component)
        if response == JFileChooser.APPROVE_OPTION:
            sf = saveDialog.getSelectedFile()
            if sf is not None:
                if sf.exists():
                    response = JOptionPane.showOptionDialog(
                        component, 'File already exists. Overwrite?',
                        'File already exists', JOptionPane.YES_NO_OPTION,
                        JOptionPane.WARNING_MESSAGE, None,
                        ['Overwrite', 'Cancel'], 'Cancel')
                    if response == JFileChooser.APPROVE_OPTION:
                        jarFile = sf
                        bFinished = True
                    else:
                        bFinished = False
                else:
                    jarFile = sf
                    bFinished = True
            else:
                bFinished = True
        else:
            bFinished = True

    if jarFile is not None:
        outStream = FileOutputStream(jarFile)

        documentBytes = document.writeAsBytes()

        nameBytesPairs = [('app.larch', documentBytes)]

        app_in_jar.buildLarchJar(outStream,
                                 nameBytesPairs,
                                 larchJarURL=chosenJarURL)

        outStream.close()
Exemple #23
0
def save(filename, pixels, w, h):
    """Save an int[] array of pixel values.
    """
    f = FileOutputStream("img.tmp")
    SaveImage.writeBytesRGB(f, pixels)
    f.close()
    print "To system"
    os.system("rawtoppm %(w)s %(h)s img.tmp | convert - %(filename)s" % locals())
    print "Done system"
Exemple #24
0
def tableDownload(cursorInstance, fileName):
    filePath = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                            'resources', fileName + '.xml')
    dataStream = FileOutputStream(filePath)
    exchange = DataBaseXMLExchange(dataStream, cursorInstance)
    exchange.downloadXML()
    dataStream.close()
    report = File(filePath)
    return JythonDownloadResult(FileInputStream(report), fileName + '.xml')
Exemple #25
0
def dump(obj, file):
    x = Xmlizer()
    xdoc = XmlDocument()
    xe = x.toXml(obj, xdoc)
    xdoc.appendChild(xe)
    #
    fos = FileOutputStream(file)
    xdoc.write(fos)
    fos.close()
 def run(self):
     while 1:
         print "Writing out channels", Date()
         ostream = FileOutputStream(self.filename)
         p = ObjectOutputStream(ostream)
         p.writeObject(self.registry.getChannelGroup("Default"))
         p.flush()
         ostream.close()
         self.sleep(self.delay)
Exemple #27
0
def writeToFile(text, testId):
    filename = "log/%s-%s-page-%d.html" % (grinder.processName,
                                       testId,
                                       grinder.runNumber)

    # Use Java FileOutputStream since it has better Unicode handling
    os = FileOutputStream(filename)
    os.write(text)
    os.close()
 def run(self):
     while 1:
         print "Writing out channels", Date()
         ostream = FileOutputStream(self.filename)
         p = ObjectOutputStream(ostream)
         p.writeObject(self.registry.getChannelGroup("Default"))
         p.flush()
         ostream.close()
         self.sleep(self.delay)
Exemple #29
0
def dump(obj,file):
    x = Xmlizer()
    xdoc = XmlDocument()
    xe = x.toXml(obj,xdoc)
    xdoc.appendChild(xe)
    #
    fos = FileOutputStream(file)
    xdoc.write(fos)
    fos.close()
 def __getFile(self, packageDir, filename):
     file = File(packageDir, filename)
     if not file.exists():
         out = FileOutputStream(file)
         IOUtils.copy(
             Services.getClass().getResourceAsStream("/workflows/" +
                                                     filename), out)
         out.close()
     return file
Exemple #31
0
def run(string, args=[], callback=None, callbackOnErr=False):
	def out (exit, call, inp, err):
		return {
			"exitCode": exit,
			"callbackReturn": call,
			"inputArray": inp,
			"errorArray": err
		}

	tmp = File.createTempFile('tmp', None)

	tmp.setExecutable(True)

	writer  = FileOutputStream(tmp);
	writer.write(string)
	writer.flush()
	writer.close()

	try:
		process = Runtime.getRuntime().exec([tmp.getAbsolutePath()] + ([str(i) for i in args] or []))
		process.waitFor()

		inp = BufferedReader(InputStreamReader(process.getInputStream()))
		err = BufferedReader(InputStreamReader(process.getErrorStream()))

		errFlag = False
		inputArray = []
		errorArray = []

		holder = inp.readLine()
		while holder != None:
			print holder
			inputArray += [holder]
			holder = inp.readLine()

		holder = err.readLine()
		while holder != None:
			errFlag = True
			errorArray += [holder]
			holder = err.readLine()

		tmp.delete()

		if errFlag:
			if callback and callbackOnErr: return out(1, callback(out(1, None, inputArray, errorArray)), inputArray, errorArray)
			else: return out(1, None, inputArray, errorArray)
		else:
			if callback: return out(0, callback(out(0, None, inputArray, [])), inputArray, [])
			else: return out(0, None, inputArray, [])
	except Exception as e:
		print str(e)

		tmp.delete()

		if callback and callbackOnErr: return out(3, callback(out(3, None, [], str(e).split("\n"))), [], str(e).split("\n"))
		else: return out(3, None, [], str(e).split("\n"))
Exemple #32
0
def writeXmlFile(fileName, xmlData):
    try:
        outputFile = "%s%s%s" % (adapterResWorkDir, FILE_SEPARATOR, fileName)
        outputStream = FileOutputStream(outputFile)
        output = XMLOutputter()
        output.output(xmlData, outputStream)
        logger.debug("Created push debug file: " + outputFile)
        outputStream.close()
    except IOError, ioe:
        logger.debug(ioe)
def make_icns(icns):
	icons = IconSuite()
	icons.setSmallIcon(generate_image(16, 16))
	icons.setLargeIcon(generate_image(32, 32))
	icons.setHugeIcon(generate_image(48, 48))
	icons.setThumbnailIcon(generate_image(128, 128))
	codec = IcnsCodec()
	out = FileOutputStream(icns)
	codec.encode(icons, out)
	out.close()
Exemple #34
0
def writeXmlFile(fileName, xmlData):
    try:
        outputFile   = "%s%s%s" % (adapterResWorkDir, FILE_SEPARATOR, fileName)
        outputStream = FileOutputStream(outputFile)
        output       = XMLOutputter()
        output.output(xmlData, outputStream)
        logger.debug("Created push debug file: " + outputFile)
        outputStream.close()
    except IOError, ioe:
        logger.debug(ioe)
def make_icns(icns):
    icons = IconSuite()
    icons.setSmallIcon(generate_image(16, 16))
    icons.setLargeIcon(generate_image(32, 32))
    icons.setHugeIcon(generate_image(48, 48))
    icons.setThumbnailIcon(generate_image(128, 128))
    codec = IcnsCodec()
    out = FileOutputStream(icns)
    codec.encode(icons, out)
    out.close()
Exemple #36
0
def tableDownload(cursorInstance, fileName):
    u"""Функция загрузки данных таблицы с объектом курсора cursorInstance в xml-файл
    """
    filePath = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                            fileName + '.xml')
    dataStream = FileOutputStream(filePath)
    exchange = DataBaseXMLExchange(dataStream, cursorInstance)
    exchange.downloadXML()
    dataStream.close()
    report = File(filePath)
    return JythonDownloadResult(FileInputStream(report), fileName + '.xml')
Exemple #37
0
def produce_jar(outdir, jarname):
    """
    Produce a jar from a directory
    
    This function does not use the 'jar' utility, so it does work on the JRE. 
    """
    fout = FileOutputStream(jarname)
    jarOut = JarOutputStream(fout)
    add_to_jar(jarOut, outdir)
    jarOut.close()
    fout.close()
    return jarname
Exemple #38
0
def exportAll():
    try:

        ALSBConfigurationMBean = findService(
            "ALSBConfiguration",
            "com.bea.wli.sb.management.configuration.ALSBConfigurationMBean")
        print "ALSBConfiguration MBean found"

        print project
        if project == "None":
            ref = Ref.DOMAIN
            collection = Collections.singleton(ref)
            if passphrase == None:
                print "Export the config"
                theBytes = ALSBConfigurationMBean.export(
                    collection, true, None)
            else:
                print "Export and encrypt the config"
                theBytes = ALSBConfigurationMBean.export(
                    collection, true, passphrase)
        else:
            ref = Ref.makeProjectRef(project)
            print "Export the project", project
            collection = Collections.singleton(ref)
            theBytes = ALSBConfigurationMBean.exportProjects(
                collection, passphrase)

        aFile = File(exportJar)
        out = FileOutputStream(aFile)
        out.write(theBytes)
        out.close()
        print "ALSB Configuration file: " + exportJar + " has been exported"

        if customFile != "None":
            print collection
            query = EnvValueQuery(
                None, Collections.singleton(EnvValueTypes.WORK_MANAGER),
                collection, false, None, false)
            customEnv = FindAndReplaceCustomization(
                'Set the right Work Manager', query,
                'Production System Work Manager')
            print 'EnvValueCustomization created'
            customList = ArrayList()
            customList.add(customEnv)
            print customList
            aFile = File(customFile)
            out = FileOutputStream(aFile)
            Customization.toXML(customList, out)
            out.close()

        print "ALSB Dummy Customization file: " + customFile + " has been created"
    except:
        raise
Exemple #39
0
def getMsgDxDirect(msgId, sl, fileName):
    storage = DXStorage(sl.getServer(), sl.getUserName(), sl.getPassword(), sl.getDomain(), "email", True, sl.getManagementServer())
    out = FileOutputStream(fileName)
    response = storage.read(str(msgId), out)
    out.flush()
    out.close()

    if not response.isSuccessful():
        printErrorToRemigrate(msgId, " from DX")
        return False
    else:
        return True
Exemple #40
0
def createGRLoaderXmlInputFile(fileName, xmlDoc):
    xmlInputFileStr = "%s%s%s" % (adapterResWorkDir, FILE_SEPARATOR, fileName)
    try:
        logger.debug("\tCreating GRLoader input XML file")
        fileOutputStream = FileOutputStream(xmlInputFileStr)
        output = XMLOutputter()
        output.output(xmlDoc, fileOutputStream)
        fileOutputStream.close()
        logger.debug("\tCreated GRLoader input XML file: %s" % xmlInputFileStr)
    except:
        raise Exception, "Unable to create GR Loader Input XML File"
    return xmlInputFileStr
def createGRLoaderXmlInputFile(fileName, xmlDoc):
    xmlInputFileStr = "%s%s%s" % (adapterResWorkDir, FILE_SEPARATOR, fileName)
    try:
        logger.debug("\tCreating GRLoader input XML file")
        fileOutputStream = FileOutputStream(xmlInputFileStr)
        output = XMLOutputter()
        output.output(xmlDoc, fileOutputStream)
        fileOutputStream.close()
        logger.debug("\tCreated GRLoader input XML file: %s" % xmlInputFileStr)
    except:
        raise Exception, "Unable to create GR Loader Input XML File"
    return xmlInputFileStr
Exemple #42
0
def mainproc():
    iMemoryRows = 100
    wb = SXSSFWorkbook(iMemoryRows)
    sh = wb.createSheet()
    for rownum in xrange(50000):
        row = sh.createRow(rownum)
        for cellnum in xrange(10):
            cell = row.createCell(cellnum)
            address = CellReference(cell).formatAsString()
            cell.setCellValue(address)
    out = FileOutputStream(outputFile)
    wb.write(out)
    out.close()
Exemple #43
0
def xmlize(xmlfile = "dsm2.xml", dsm2file = "dsm2.inp"):
  """
  xmlize(xmlfile = "dsm2.xml", dsm2file = "dsm2.inp")
    xmlizes a dsm2file into an xml file
  """
  parser = DSM2Parser(dsm2file)
  from java.io import FileOutputStream
  try:
    from com.sun.xml.tree import XmlDocument
  except:
    print 'Xml.jar not in classpath'
  xdoc = parser.dsm2_data.toXml()
  fos = FileOutputStream(xmlfile)
  xdoc.write(fos)
  fos.close()
Exemple #44
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 #45
0
def getMsgDxDirect(someMsgId, sl, fileName, threadName):
    printQueue.add("debug("+ threadName +"): entering getMsgDxDirect() with someMsgId = " + str(someMsgId))
    storage = DXStorage(sl.getServer(), sl.getUserName(), sl.getPassword(), sl.getDomain(), "email", True, sl.getManagementServer())
    out = FileOutputStream(fileName)
    response = storage.read(str(someMsgId), out)
    printQueue.add("debug("+ threadName +"): dx response is " + str(response.toString()) + " with someMsgId = " + str(someMsgId))
    out.flush()
    out.close()

    if not response.isSuccessful():
        printErrorToRemigrate(someMsgId, " from DX")
        return False
    else:
        printQueue.add("debug("+ threadName +"): exiting successfully getMsgDxDirect() with someMsgId = " + str(someMsgId))
        return True
Exemple #46
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()
def unzipFile(zipFile, outputFolder):
    zis = ZipInputStream(FileInputStream(zipFile))
    ze = zis.getNextEntry()
    while ze != None:
        fileName = ze.getName()
        newFile = File(outputFolder + File.separator + fileName)
        print("file unzip : " + str(newFile.getAbsoluteFile()))
        File(newFile.getParent()).mkdirs()
        fos = FileOutputStream(newFile)
        len = zis.read()
        while len > 0:
            fos.write(len)
            len = zis.read()
        fos.close()
        ze = zis.getNextEntry()
    zis.closeEntry()
    zis.close()
Exemple #48
0
    def write_epub(self, overwrite=False):
        self._put_mimetype(overwrite)
        self._put_metainf(overwrite)
        self._put_oebps()
        self._put_tocncx(overwrite)
        self.process_content(overwrite, self.fullpath('OEBPS'))
        self._put_contentopf(overwrite)

        archiveStream = FileOutputStream(self.epub)
        archive = ArchiveStreamFactory().createArchiveOutputStream(
            ArchiveStreamFactory.ZIP, archiveStream)
        archive.setLevel(Deflater.NO_COMPRESSION)
        self.write(archive, self.fullpath('mimetype'), 'mimetype')
        archive.setLevel(Deflater.DEFLATED)
        self.write(archive, self.fullpath('META-INF', 'container.xml'),
                   'META-INF/container.xml')
        self.recursive_pack(archive, self.fullpath('OEBPS'))
        archive.finish()
        archiveStream.close()
Exemple #49
0
 def extract_tools_data_from_jar_files(self):
     """Create tools directories from JAR files with tools data
        Read directories from tools/data and create jar files in tools/jar
     """
     jarDir = File(self.jarDir)
     for jarFileName in jarDir.list():
         toolDir = File.separator.join([self.toolsDir, jarFileName[:-4]])
         self.delete_old_tool_directory(File(toolDir))
         jar = JarFile(File(self.jarDir, jarFileName))
         for entry in jar.entries():
             f = File(File.separator.join([self.toolsDir, entry.getName()]))
             if entry.isDirectory():
                 f.mkdir()
                 continue
             inputStream = jar.getInputStream(entry)
             fos = FileOutputStream(f)
             while inputStream.available() > 0:
                 fos.write(inputStream.read())
             fos.close()
             inputStream.close()
Exemple #50
0
 def _get_file(self, remote_path, local_path):
     local_file = FileOutputStream(local_path)
     remote_file_size = self._client.stat(remote_path).size
     remote_file = self._client.openFileRO(remote_path)
     array_size_bytes = 4096
     data = jarray.zeros(array_size_bytes, 'b')
     offset = 0
     while True:
         read_bytes = self._client.read(remote_file, offset, data, 0,
                                        array_size_bytes)
         data_length = len(data)
         if read_bytes == -1:
             break
         if remote_file_size - offset < array_size_bytes:
             data_length = remote_file_size - offset
         local_file.write(data, 0, data_length)
         offset += data_length
     self._client.closeFile(remote_file)
     local_file.flush()
     local_file.close()
Exemple #51
0
def serialize(obj, filepath):
  if not Serializable.isAssignableFrom(obj.getClass()):
    syncPrintQ("Object doesn't implement Serializable: " + str(obj))
    return False
  f = None
  o = None
  try:
    f = FileOutputStream(filepath)
    o = ObjectOutputStream(f)
    o.writeObject(obj)
    o.flush()
    f.getFD().sync() # ensure file is written to disk
    return True
  except:
    syncPrintQ(sys.exc_info())
  finally:
    if o:
      o.close()
    if f:
      f.close()
Exemple #52
0
    def __createPackage(self, outputFile=None):
        title = self.__manifest.getString(None, "title")
        manifest = self.__createManifest()
        context = JAXBContext.newInstance("com.googlecode.fascinator.ims")
        m = context.createMarshaller()
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, True)
        writer = StringWriter()
        jaxbElem = ObjectFactory.createManifest(ObjectFactory(), manifest)
        m.marshal(jaxbElem, writer)
        writer.close()

        if outputFile is not None:
            print "writing to %s..." % outputFile
            out = FileOutputStream(outputFile)
        else:
            print "writing to http output stream..."
            filename = urllib.quote(title.replace(" ", "_"))
            response.setHeader("Content-Disposition",
                               "attachment; filename=%s.zip" % filename)
            out = response.getOutputStream("application/zip")

        zipOut = ZipOutputStream(out)

        zipOut.putNextEntry(ZipEntry("imsmanifest.xml"))
        IOUtils.write(writer.toString(), zipOut)
        zipOut.closeEntry()

        oidList = self.__manifest.search("id")
        for oid in oidList:
            obj = Services.getStorage().getObject(oid)
            for pid in obj.getPayloadIdList():
                payload = obj.getPayload(pid)
                if not PayloadType.Annotation.equals(payload.getType()):
                    zipOut.putNextEntry(
                        ZipEntry("resources/%s/%s" % (oid, pid)))
                    IOUtils.copy(payload.open(), zipOut)
                    payload.close()
                    zipOut.closeEntry()
            obj.close()
        zipOut.close()
        out.close()