def main(): ''' The main section to determine is the script is executed within or outside of the CAVI environment ''' if cavi_env: # This is all the stuff to do if in the CAVI script_name = "{}.py".format(arg2) tw = cavistatus.get_timewindow() if tw == None: msg = "No forecast open on Modeling tab to get a timewindow." cumulus_logger.warning(msg) MessageBox.showWarning(msg, "No Forecast Open" ) sys.exit() db = os.path.join(cavistatus.get_database_directory(), "grid.dss") cwms_home = cavistatus.get_working_dir() common_exe = os.path.join(os.path.split(cwms_home)[0], "common", "exe") cumulus_logger.debug("DSS file default: {}".format(db)) cumulus_logger.debug("CWMS working directory: {}".format(cwms_home)) cumulus_logger.debug("Jython execution directory: {}".format(common_exe)) cumulus_config = os.path.join(APPDATA, "cumulus.config") this_script = os.path.join(cavistatus.get_project_directory(), "scripts", script_name) cmd = "@PUSHD {pushd}\n" cmd += '@Jython.bat "{script}" ' cmd += '"{start}" "{end}" "{dss}" "{home}" "{config}"' cmd = cmd.format(pushd=common_exe, script=this_script, start=tw[0], end=tw[1], dss=db, home=cwms_home, config=cumulus_config ) # Create a temporary file that will be executed outside the CAVI env batfile = tempfile.NamedTemporaryFile(mode='w', suffix='.cmd', delete=False) batfile.write(cmd) batfile.close() cumulus_logger.info("Initiated Subprocess") p = subprocess.Popen("start cmd /C " + batfile.name, shell=True) # os.remove(batfile.name) else: # This is all the stuff to do if initiated outside the CAVI environment args = sys.argv[1:] if len(args) < 5: MessageBox.showPlain( "Expecting five arguments. {} arguments given".format(len(args)), "Exception" ) raise Exception("Need more arguments") keys = ['start_time', 'end_time', 'dss_path', 'cwms_home', 'config'] ordered_dict = dict(zip(keys, args)) # Set the look and feel # Metal, Nimbus, CDE/Motif, Windows, or Windows Classic LookAndFeel("Nimbus") cui = CumulusUI(ordered_dict) cui.setVisible(True)
def json_build(self): '''Return JSON string or 'None' if failed The returning JSON string is from the UI and used when POSTing to the Cumulus API. ''' conf = { 'datetime_start': None, 'datetime_end': None, 'watershed_id': None, 'product_id': None, } try: tf = TimeFormatter() tz = tf.zid st = tf.parse_zoned_date_time(self.txt_start_time.getText(), tz) et = tf.parse_zoned_date_time(self.txt_end_time.getText(), tz) conf['datetime_start'] = st.format(tf.iso_instant()) conf['datetime_end'] = et.format(tf.iso_instant()) except DateTimeParseException as ex: MessageBox.showWarning(ex, "Exception") selected_watershed = self.lst_watershed.getSelectedValue() selected_products = self.lst_product.getSelectedValues() if selected_watershed is not None: watershed_id = self.basin_meta[selected_watershed]['id'] conf['watershed_id'] = watershed_id else: MessageBox.showWarning( "No Watershed Selected", "Exception" ) return None product_ids = list() if len(selected_products) > 0: for p in selected_products: product_ids.append(self.product_meta[p]['id']) conf['product_id'] = product_ids else: MessageBox.showWarning( "No Products Selected", "Exception" ) return None return json.dumps(conf)
def submit(self, event): '''Collect user inputs and initiate download of DSS files to process. Event is a java.awt.event.ActionEvent ''' start_timer = end_timer = System.currentTimeMillis() # Build the JSON from the UI inputs and POST if we have JSON json_string = self.json_build() cumulus_logger.debug("JSON String Builder: {}".format(json_string)) if json_string is not None: cumulus_logger.info("*" * 50) cumulus_logger.info("Initiated Cumulus Product Request") cumulus_logger.info("*" * 50) post_result = self.http_post(json_string, url_downloads) json_post_result = json.loads(post_result) id = json_post_result['id'] max_timeout = 180 while max_timeout > 0: get_result = self.http_get("/".join([url_downloads, id])) if get_result is not None: json_get_result = json.loads(get_result) progress = json_get_result['progress'] #100% stat = json_get_result['status'] #SUCCESS fname = json_get_result['file'] # not null cumulus_logger.info("Status: {:>10}; Progress: {:>4.1f}%; Timeout: {:>4}".format(stat, progress, max_timeout)) if stat == 'FAILED': cumulus_logger.error("Failed to load grid products.") MessageBox.showError( "Failed to load grid products.", "Failed Download" ) break if int(progress) == 100 and stat == 'SUCCESS' and fname is not None: dest_dssfile = self.txt_select_file.getText() cumulus_logger.debug("DSS Download Filname: {}".format(fname)) downloaded_dssfile = download_dss(fname) if downloaded_dssfile is not None: cumulus_logger.info("DSS file downloaded.") merged_dssfiles = merge_dss(downloaded_dssfile, dest_dssfile) if len(merged_dssfiles) > 0: end_timer = System.currentTimeMillis() msg = "DSS file downloaded and merged to: {}".format( '\n'.join([f for f in merged_dssfiles]) ) cumulus_logger.info(msg) MessageBox.showInformation(msg, "Successful Processing" ) else: msg = "DSS file merge unsuccessful" cumulus_logger.warning(msg) MessageBox.showWarning(msg, "Unsuccessful Merge" ) else: msg = "Downloading and processing the DSS file failed!" cumulus_logger.error(msg) MessageBox.showError(msg, "Failed Processing" ) break else: Thread.sleep(2000) max_timeout -= 1 cumulus_logger. info( "Submit time duration (milliseconds): {}".format( (end_timer - start_timer) ) ) # Try to clean up any dss6 and dss7 files in the temp try: tempdir = tempfile.gettempdir() dss_temp_files = os.listdir(tempdir) for f in dss_temp_files: if (f.endswith(".dss") or f.endswith(".dss")): os.remove(os.path.join(tempdir, f)) except OSError as ex: cumulus_logger.warning(str(ex))