def extract_file_from_jar(config_file):
    file_url = LoaderUtil.getResourceBySelfClassLoader(config_file)
    if file_url:
        tmp_file, tmp_abs_path = tempfile.mkstemp()
        tmp_file.close()
        Files.copy(file_url.openStream(), Paths.get(tmp_abs_path), StandardCopyOption.REPLACE_EXISTING)
        return tmp_abs_path
    else:
        return None
Beispiel #2
0
    def doInBackground(self):
        #Initialize progress property.
        progress = 0
        self.super__setProgress(progress)

        # "\n download tools list"
        progress = 2
        self.super__setProgress(progress)
        self.delete_file(self.tmpToolsListFile)

        if not self.download_file(self.app.toolsListUrl,
                                  self.tmpToolsListFile):
            # " I cannot download the tools list."
            progress = 3
            self.super__setProgress(progress)
            return

        toolsRefs = read_tools_list(self.tmpToolsListFile)

        #Download tools data as jar files
        progress = 5
        self.super__setProgress(progress)
        self.jarDir = File.separator.join([self.app.SCRIPTDIR, "tools", "jar"])
        if not File(self.jarDir).exists():
            File(self.jarDir).mkdir()
        else:
            #delete old files
            for jarFileName in File(self.jarDir).list():
                File(File.separator.join([self.jarDir, jarFileName])).delete()
        #download new files
        for toolRef in toolsRefs:
            jarFileName = "%s.jar" % toolRef
            jarUrl = "%s/%s" % (self.app.jarBaseUrl, jarFileName)
            jarFilePath = File.separator.join([self.jarDir, jarFileName])
            answer = self.download_file(jarUrl, jarFilePath)
            if not answer:
                # " I cannot download the tools file"
                progress = 6
                self.super__setProgress(progress)
                return

        #Extract tools data from jar files
        self.toolsDir = File.separator.join(
            [self.app.SCRIPTDIR, "tools", "data"])
        progress = 7
        self.super__setProgress(progress)
        self.extract_tools_data_from_jar_files()

        #Remove temporary file
        self.delete_file(self.toolsListFile)
        Files.copy(Paths.get(self.tmpToolsListFile),
                   Paths.get(self.toolsListFile))
        self.delete_file(self.tmpToolsListFile)

        progress = 8
        self.super__setProgress(progress)
def extract_file_from_jar(config_file):
    file_url = LoaderUtil.getResourceBySelfClassLoader(config_file)
    if file_url:
        tmp_file, tmp_abs_path = tempfile.mkstemp()
        tmp_file.close()
        Files.copy(file_url.openStream(), Paths.get(tmp_abs_path),
                   StandardCopyOption.REPLACE_EXISTING)
        return tmp_abs_path
    else:
        return None
Beispiel #4
0
    def doInBackground(self):
        #Initialize progress property.
        progress = 0
        self.super__setProgress(progress)

        # "\n download tools list"
        progress = 2
        self.super__setProgress(progress)
        self.delete_file(self.tmpToolsListFile)

        if not self.download_file(self.app.toolsListUrl, self.tmpToolsListFile):
            # " I cannot download the tools list."
            progress = 3
            self.super__setProgress(progress)
            return

        toolsRefs = read_tools_list(self.tmpToolsListFile)

        #Download tools data as jar files
        progress = 5
        self.super__setProgress(progress)
        self.jarDir = File.separator.join([self.app.SCRIPTDIR, "tools", "jar"])
        if not File(self.jarDir).exists():
            File(self.jarDir).mkdir()
        else:
            #delete old files
            for jarFileName in File(self.jarDir).list():
                File(File.separator.join([self.jarDir, jarFileName])).delete()
        #download new files
        for toolRef in toolsRefs:
            jarFileName = "%s.jar" % toolRef
            jarUrl = "%s/%s" % (self.app.jarBaseUrl, jarFileName)
            jarFilePath = File.separator.join([self.jarDir, jarFileName])
            answer = self.download_file(jarUrl, jarFilePath)
            if not answer:
                # " I cannot download the tools file"
                progress = 6
                self.super__setProgress(progress)
                return

        #Extract tools data from jar files
        self.toolsDir = File.separator.join([self.app.SCRIPTDIR, "tools", "data"])
        progress = 7
        self.super__setProgress(progress)
        self.extract_tools_data_from_jar_files()

        #Remove temporary file
        self.delete_file(self.toolsListFile)
        Files.copy(Paths.get(self.tmpToolsListFile), Paths.get(self.toolsListFile))
        self.delete_file(self.tmpToolsListFile)

        progress = 8
        self.super__setProgress(progress)
def decompress_file(archived_file, unarchived_file):
    '''
    FUNC TO DECOMPRESS BZIP2 ARCHIVE
    '''
    ins_log("Decompressing...", str(archived_file))
    try:
        gzis = BZip2CompressorInputStream(FileInputStream(archived_file))
        Files.copy(gzis, Paths.get(unarchived_file),
                   StandardCopyOption.REPLACE_EXISTING)
    except Exception:
        ins_log('Decompressing error', str(Exception))
    ins_log("File Decompressed!", str(unarchived_file))
Beispiel #6
0
 def download_file(self, url, filePath):
     """Downloads a file form url and save it as filePath
     """
     try:
         print "\ndownloading"
         print url
         print filePath
         inputStream = URI.create(url).toURL().openStream()
         Files.copy(inputStream, Paths.get(filePath))
         return True
     except (UnknownHostException, SocketException), e:
         print e
         print "I cannot download:\n%s" % url
         return False
Beispiel #7
0
 def download_file(self, url, filePath):
     """Downloads a file form url and save it as filePath
     """
     try:
         print "\ndownloading"
         print url
         print filePath
         inputStream = URI.create(url).toURL().openStream()
         Files.copy(inputStream, Paths.get(filePath))
         return True
     except (UnknownHostException, SocketException), e:
         print e
         print "I cannot download:\n%s" % url
         return False
    def undeploy_package(self, zipped_package):
        working_dir, working_dir_path, undeploy_package_path = self._setup_working_dir()

        try:
            unzipped_package_path = Files.createDirectory(working_dir.resolve("undeploy_root"))
            self._extract_package(zipped_package, str(unzipped_package_path.toAbsolutePath()))
            package_xml_file = unzipped_package_path.resolve("package.xml")
            root = ET.parse(str(package_xml_file.toAbsolutePath())).getroot()
            ns = {'sf': 'http://soap.sforce.com/2006/04/metadata'}
            version = root.find('sf:version', ns).text

            Files.copy(package_xml_file, undeploy_package_path.resolve('destructiveChanges.xml'))
            Files.write(undeploy_package_path.resolve("package.xml"), bytearray(self.empty_package_template(version)))

            for output in self._execute(working_dir):
                print output
        finally:
            FileUtils.deleteDirectory(working_dir.toFile())
Beispiel #9
0
def download_dss(dss_url):
    '''
    Return java.nio.file.Path temp_dssfile

    Inputs: java.lang.String DSS URI
    DSS file downloaded to user's temporary directory as to not clober any existing
    DSS file and all records written to DSS OUT Path.
    '''
    start_timer = System.currentTimeMillis()
    result = None
    try:
        # Create input stream reader to read the file
        url = URL(dss_url)
        urlconnect = url.openConnection()
        response_code = urlconnect.getResponseCode()
        if response_code == 200:
            input_stream = urlconnect.getInputStream()
            temp7dss = Files.createTempFile("dss7_", ".dss")
            Files.copy(input_stream,
                temp7dss,
                StandardCopyOption.REPLACE_EXISTING
                )
            input_stream.close()
            result = temp7dss
    except IOException as ex:
        # MessageBox.showError(str(ex), "Exception")
        raise

    end_timer = System.currentTimeMillis()
    cumulus_logger.debug(
        "DSS Download (milliseconds): {}".format(
            (end_timer - start_timer)
        )
    )

    return result
Beispiel #10
0
    def loadResource(self, u) :
        sysloader = self.java.lang.ClassLoader.getSystemClassLoader()
        return sysloader.getResourceAsStream(u)

import java.nio.file.Files as Files
import java.nio.file.Paths as Paths
import java.lang.System as System
import java.util.List
from java.awt import *
import ucar.unidata.idv.DefaultIdv as DefaultIdv
import ucar.unidata.idv.ui.ImageGenerator as ImageGenerator

idv = DefaultIdv([])
islInterpreter = ImageGenerator(idv)

# need to load a few resources from the classpath

my_files = ["ucar/unidata/idv/resources/python/shell.py",
           "ucar/unidata/idv/resources/python/isl.py"]

cpl = resourceLoader()
tmpfile = System.getProperty("java.io.tmpdir") + "/idv.py"

for f in my_files:
    inpstr = cpl.loadResource(f)
    path = Paths.get(tmpfile)
    Files.copy(inpstr, path)
    execfile(tmpfile)
    Files.delete(path)
Beispiel #11
0
    def show(self):
        #Root Pane
        root = VBox()
        #FXML Loader
        fxmlLoader = FXMLLoader()

        #TextArea
        from javafx.scene.control import TextArea
        textArea = TextArea("Loading . . .")

        #Configure Text Area
        textArea.setEditable(False)
        textArea.setPrefHeight(600)

        #Bottom Bar, Current Stylesheet
        if self.app.getCurrentTheme() == "Dark":
            fxmlLoader.setLocation(
                File("../resources/fxml/history_url_tab_dark.fxml").toURI().
                toURL())  #For some odd reason this is broken?
            bottom_bar = self.app.bottom_bar_dt
        elif self.app.getCurrentTheme() == "Light":
            fxmlLoader.setLocation(
                File("../resources/fxml/history_url_tab_light.fxml").toURI().
                toURL())
            bottom_bar = ImageView(
                Image(
                    String(
                        File('../resources/icons/bottom_bar_lt.png').toURI().
                        toString()), True))
        #Think about future themes
        else:
            pass

        #URL Bar
        try:
            url_bar = fxmlLoader.load(
            )  #BROKEN - For some reason this breaks after a couple toggles.
        except LoadException as e:
            print('Log: Exception: An FXML Load Exception has occured.' +
                  str(e.getCause()))

        #Add Children to root pane
        root.getChildren().addAll(url_bar, textArea, bottom_bar)

        #Fill Width, assume Theme of Main Stage
        root.setFillWidth(True)

        #Set scene, title
        scene = Scene(root, 1350, 625)

        #We are leaving the default controls for now.

        #Make sure the Text Area's scroll bar is always visible.
        scene.getStylesheets().add(
            File("../resources/themes/text-area_scroll-pane.css").toURI().
            toString())
        self.stage.setScene(scene)
        self.stage.setTitle("History - EmeraldFX")

        #Position History Stage
        self.stage.setX(self.app.getMainStage().getX())
        self.stage.setY(self.app.getMainStage().getY() + 52)

        #Display History Stage
        self.stage.show()

        #It is CSV, let us display as plain text.
        history_csv = File("../resources/history/HISTORY.csv")
        history_txt = File("../resources/history/HISTORY.txt")

        #Delete text copy if it exists
        history_txt.delete() if history_txt.exists() else None

        #Copy
        Files.copy(history_csv.toPath(), history_txt.toPath())

        #Prevent Resizing
        self.stage.setResizable(False)

        #Flush Stream
        self.BS.triggerHistoryWrite()

        #GetController instance
        controller = fxmlLoader.getController()
        ''' Failed Attempts '''

        #WebView
        # webView = WebView()
        #Grab Web Engine
        # webEng = webView.getEngine()
        #Enable JS
        # webEng.setJavaScriptEnabled(True)

        #Attempt #1 - Start scrolling from the bottom - FAILED
        # webEng.executeScript("window.scrollTo(" + "0" + ", " + "600" + ");")

        #Attempt #2 - Scroll Pane - FAILED
        # from javafx.scene.control import ScrollPane
        # wv_scroll = ScrollPane()
        # wv_scroll.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS)
        # wv_scroll.setContent(webView)
        # wv_scroll.setFitToWidth(True)
        # wv_scroll.setFitToHeight(True)
        # wv_scroll.setVvalue(wv_scroll.getVmin())

        #Load History
        # try:
        # webEng.load(history_txt.toURI().toString())
        # except Exception as e:
        # print ('Log: Load Exception: Error Loading History: ' + str(e.getCause()))
        # return

        #Attempt #3 - Execute Script for Scroll Bar - FAILD
        # webEng.executeScript(
        # "function scrollDown() { window.scrollTo(0,400); }" +
        # "scrollDown();"
        # )

        #Set Position of Scroll Bar
        class AnonInnerCL_TA(ChangeListener):
            """Inner Class for Scrolling Down"""
            def __init__(self, textArea):
                self.textArea = textArea

            #@Override
            def changed(self, observable, old, new):
                if new > old:
                    from java.lang import Double
                    self.textArea.setScrollTop(Double.MAX_VALUE)
                else:
                    pass

        textArea.textProperty().addListener(AnonInnerCL_TA(textArea))

        #Show History after it is loaded
        if self.stage.isShowing(
        ):  #May or may not be broken. If there is litle to no delay, "Loading . . ." will not be noticed.
            #Load History on separate thread.
            #Clear initial text: Loading . . .
            textArea.clear()
            #Instantate Service
            service = HistoryService(history_txt, textArea)
            #Algorithm improved. Start service
            service.start()
        '''Add resources to controller'''
        #Theme Resources
        controller.addThemeResources(
            self.app.getMainStage(), self.stage,
            self.app.getMainStage().getScene(), self.app.getCurrentTheme(),
            textArea
        )  #(Stage mainStage, Stage histStage, Scene scene, String theme, TextArea textArea)
        #Clear Resource
        controller.addClearResources(self.BS.isHistoryCleared())  #(boolean)
        #Quit Resources
        controller.addQuitResources(
            self.app.getAllStages(),
            self.BS.getHistoryWriter())  #(List<Stages>, PrintWriter)
        #Media Resources
        MMC = self.app.getMediaControls()
        controller.addMediaResources(MMC)

        #Create Bidirectional Bindings between Main Stage's media controls and history's controls
        from javafx.beans.binding import Bindings

        MMC_IT = MMC.listIterator()
        HMC = controller.getMediaControls()

        #Set history media controls to current state
        class HMCC(Consumer):
            def __init__(self, MMC_IT):
                self.MMC_IT = MMC_IT

            #@Override
            def accept(self, button):
                button.setDisabled(MMC_IT.next().isDisabled())

        HMC.forEach(HMCC(MMC_IT))

        #Fails - first arg cannot be coerced into Consumer? Odd.
        # history_media_controls.forEach(lambda button: button.setDisabled( main_media_controls.forEach(lambda button: button.isDisabled()) ) )

        #Play
        #Won't work -- read only property does not inherit Property, seperate API.
        # Bindings.bindBidirectional(history_media_controls.get(0).disabledProperty(), main_media_controls[0].disabledProperty() )
        #Stop
        # Bindings.bindBidirectional(history_media_controls.get(1).disabledProperty(), main_media_controls[1].disabledProperty() )
        #Previous
        # Bindings.bindBidirectional(history_media_controls.get(2).disabledProperty(), main_media_controls[2].disabledProperty() )
        #Next
        # Bindings.bindBidirectional(history_media_controls.get(3).disabledProperty(), main_media_controls[3].disabledProperty() )

        #Shortcut Keys Allowed for History (CTRL + D, CTRL + Q, CTRL + T)
        scene.addEventFilter(
            KeyEvent.KEY_PRESSED, lambda event: self.handleHistoryShortcuts(
                event, self.BS, controller.getToggleTheme(),
                controller.getClearHistory()))

        #Python needs to fix lambdas so we don't have to resort to wrapping inner classes in collections. Yuck.
        class HistoryClosed:
            @staticmethod
            def printClosed():
                print("Log: Quit Action: History just closed.")

        #Switch back to the main stage
        self.stage.setOnCloseRequest(lambda event: [
            self.app.getMainStage().toFront(),
            self.stage.close(),
            HistoryClosed.printClosed()
        ])

        #Log
        print('Log: History Notification: History data displayed @ ' +
              str(LocalDateTime.now()))
Beispiel #12
0
        return sysloader.getResourceAsStream(u)


import java.nio.file.Files as Files
import java.nio.file.Paths as Paths
import java.lang.System as System
import java.util.List
from java.awt import *
import ucar.unidata.idv.DefaultIdv as DefaultIdv
import ucar.unidata.idv.ui.ImageGenerator as ImageGenerator

idv = DefaultIdv([])
islInterpreter = ImageGenerator(idv)

# need to load a few resources from the classpath

my_files = [
    "ucar/unidata/idv/resources/python/shell.py",
    "ucar/unidata/idv/resources/python/isl.py"
]

cpl = resourceLoader()
tmpfile = System.getProperty("java.io.tmpdir") + "/idv.py"

for f in my_files:
    inpstr = cpl.loadResource(f)
    path = Paths.get(tmpfile)
    Files.copy(inpstr, path)
    execfile(tmpfile)
    Files.delete(path)