List of usage examples for javax.swing SwingWorker addPropertyChangeListener
public final void addPropertyChangeListener(PropertyChangeListener listener)
From source file:edu.ku.brc.specify.config.init.secwiz.DatabasePanel.java
/** * /*from w w w. jav a2 s .c om*/ */ public void createDB() { getValues(properties); final String databaseName = dbNameTxt.getText(); final String dbUserName = usernameTxt.getText(); final String dbPwd = passwordTxt.getText(); final String hostName = hostNameTxt.getText(); if (isMobile()) { DBConnection.clearMobileMachineDir(); File tmpDir = DBConnection.getMobileMachineDir(databaseName); setEmbeddedDBPath(tmpDir.getAbsolutePath()); } final DatabaseDriverInfo driverInfo = (DatabaseDriverInfo) drivers.getSelectedItem(); String connStrInitial = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open, hostName, databaseName, dbUserName, dbPwd, driverInfo.getName()); //System.err.println(connStrInitial); DBConnection.checkForEmbeddedDir("createDB - " + connStrInitial); DBConnection.getInstance().setDriverName(driverInfo.getName()); DBConnection.getInstance().setServerName(hostName); VerifyStatus status = verifyDatabase(properties); if ((isOK == null || !isOK) && status == VerifyStatus.OK) { progressBar.setIndeterminate(true); progressBar.setVisible(true); label.setText(getResourceString("CONN_DB")); setUIEnabled(false); DatabasePanel.this.label.setForeground(Color.BLACK); SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() { /* (non-Javadoc) * @see javax.swing.SwingWorker#doInBackground() */ @Override protected Object doInBackground() throws Exception { isOK = false; DBMSUserMgr mgr = DBMSUserMgr.getInstance(); boolean dbmsOK = false; if (driverInfo.isEmbedded()) { if (checkForProcesses) { SpecifyDBSecurityWizardFrame.checkForMySQLProcesses(); checkForProcesses = false; } if (isMobile()) { File mobileTmpDir = DBConnection.getMobileMachineDir(); if (!mobileTmpDir.exists()) { if (!mobileTmpDir.mkdirs()) { System.err.println( "Dir[" + mobileTmpDir.getAbsolutePath() + "] didn't get created!"); // throw exception } DBConnection.setCopiedToMachineDisk(true); } } String newConnStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open, hostName, databaseName, dbUserName, dbPwd, driverInfo.getName()); if (driverInfo.isEmbedded()) { //System.err.println(newConnStr); try { Class.forName(driverInfo.getDriverClassName()); // This call will create the database if it doesn't exist DBConnection testDB = DBConnection.createInstance(driverInfo.getDriverClassName(), driverInfo.getDialectClassName(), databaseName, newConnStr, dbUserName, dbPwd); testDB.getConnection(); // Opens the connection if (testDB != null) { testDB.close(); } dbmsOK = true; } catch (Exception ex) { ex.printStackTrace(); } DBConnection.getInstance().setDatabaseName(null); } } else if (mgr.connectToDBMS(dbUserName, dbPwd, hostName)) { mgr.close(); dbmsOK = true; } if (dbmsOK) { firePropertyChange(PROPNAME, 0, 1); try { SpecifySchemaGenerator.generateSchema(driverInfo, hostName, databaseName, dbUserName, dbPwd); // false means create new database, true means update String connStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Create, hostName, databaseName); if (connStr == null) { connStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open, hostName, databaseName); } firePropertyChange(PROPNAME, 0, 2); // tryLogin sets up DBConnection if (UIHelper.tryLogin(driverInfo.getDriverClassName(), driverInfo.getDialectClassName(), dbNameTxt.getText(), connStr, dbUserName, dbPwd)) { if (!checkEngineCharSet(properties)) { return false; } isOK = true; firePropertyChange(PROPNAME, 0, 3); Thumbnailer thumb = Thumbnailer.getInstance(); File thumbFile = XMLHelper.getConfigDir("thumbnail_generators.xml"); thumb.registerThumbnailers(thumbFile); thumb.setQuality(.5f); thumb.setMaxSize(128, 128); File attLoc = getAppDataSubDir("AttachmentStorage", true); AttachmentManagerIface attachMgr = new FileStoreAttachmentManager(attLoc); AttachmentUtils.setAttachmentManager(attachMgr); AttachmentUtils.setThumbnailer(thumb); } else { errorKey = "NO_LOGIN_ROOT"; } } catch (Exception ex) { errorKey = "DB_UNRECOVERABLE"; } } else { errorKey = "NO_CONN_ROOT"; mgr.close(); } return null; } /* (non-Javadoc) * @see javax.swing.SwingWorker#done() */ @Override protected void done() { super.done(); setUIEnabled(true); progressBar.setIndeterminate(false); progressBar.setVisible(false); updateBtnUI(); if (isOK) { label.setText(getResourceString("DB_CREATED")); setUIEnabled(false); } else { label.setText(getResourceString(errorKey != null ? errorKey : "ERR_CRE_DB")); showLocalizedError(errorKey != null ? errorKey : "ERR_CRE_DB"); } } }; worker.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent evt) { if (PROPNAME.equals(evt.getPropertyName())) { String key = null; switch ((Integer) evt.getNewValue()) { case 1: key = "BLD_SCHEMA"; break; case 2: key = "DB_FRST_LOGIN"; break; case 3: key = "BLD_CACHE"; break; default: break; } if (key != null) { DatabasePanel.this.label.setText(getResourceString(key)); } } } }); worker.execute(); } else if (status == VerifyStatus.ERROR) { errorKey = "NO_LOGIN_ROOT"; DatabasePanel.this.label.setText(getResourceString(errorKey)); DatabasePanel.this.label.setForeground(Color.RED); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { getTopWindow().pack(); } }); } }
From source file:edu.ku.brc.specify.dbsupport.SpecifySchemaUpdateService.java
/** * Changes all the contents of the Geography 'Name' field from the geonames 'name' to 'acsiiname' to * get rid of the unprintable ascii characters. *///from w ww.jav a 2 s. c o m public void updateGeographyNames() { final String FIXED_GEO = "FIXED.GEOGRAPHY"; if (AppPreferences.getGlobalPrefs().getBoolean(FIXED_GEO, false)) { //return; } String sql = String.format( "SELECT COUNT(*) FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME = 'geoname'", DBConnection.getInstance().getDatabaseName()); if (BasicSQLUtils.getCount(sql) == 0) { AppPreferences.getGlobalPrefs().putBoolean(FIXED_GEO, true); return; } final int numRecs = BasicSQLUtils.getCountAsInt( "SELECT COUNT(*) FROM geoname ge INNER JOIN geography g ON ge.name = g.Name WHERE ge.Name <> ge.asciiname"); if (BasicSQLUtils.getCount(sql) == 0) { AppPreferences.getGlobalPrefs().putBoolean(FIXED_GEO, true); return; } final ProgressFrame prefProgFrame = new ProgressFrame(getResourceString("UPDATE_SCHEMA_TITLE")); prefProgFrame.adjustProgressFrame(); prefProgFrame.getCloseBtn().setVisible(false); prefProgFrame.getProcessProgress().setIndeterminate(true); prefProgFrame.setDesc(UIRegistry.getLocalizedMessage("UPDATE_GEO")); UIHelper.centerAndShow(prefProgFrame); prefProgFrame.setProcess(0, 100); SwingWorker<Boolean, Boolean> worker = new SwingWorker<Boolean, Boolean>() { @Override protected Boolean doInBackground() throws Exception { Statement stmt = null; PreparedStatement pStmt = null; try { Connection currDBConn = DBConnection.getInstance().getConnection(); pStmt = currDBConn.prepareStatement("UPDATE geography SET Name=? WHERE GeographyID=?"); stmt = currDBConn.createStatement(); int cnt = 0; String sqlStr = "SELECT ge.asciiname, g.GeographyID FROM geoname ge INNER JOIN geography g ON ge.name = g.Name WHERE ge.Name <> ge.asciiname"; ResultSet rs = stmt.executeQuery(sqlStr); while (rs.next()) { pStmt.setString(1, rs.getString(1)); pStmt.setInt(2, rs.getInt(2)); if (pStmt.executeUpdate() != 1) { } cnt++; if (prefProgFrame != null && cnt % 100 == 0) { setProgress((int) (cnt / numRecs * 100.0)); } } rs.close(); if (prefProgFrame != null) { prefProgFrame.setProcess(numRecs); } AppPreferences.getGlobalPrefs().putBoolean(FIXED_GEO, true); } catch (Exception ex) { ex.printStackTrace(); edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(BuildFromGeonames.class, ex); } finally { try { if (stmt != null) { stmt.close(); } if (pStmt != null) { pStmt.close(); } } catch (Exception ex) { ex.printStackTrace(); } } return true; } /* (non-Javadoc) * @see javax.swing.SwingWorker#done() */ @Override protected void done() { super.done(); prefProgFrame.setVisible(false); prefProgFrame.dispose(); } }; worker.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent evt) { if ("progress".equals(evt.getPropertyName())) { prefProgFrame.setProcess((Integer) evt.getNewValue()); } } }); worker.execute(); }
From source file:edu.ku.brc.af.core.db.MySQLBackupService.java
/** * Does the backup on a SwingWorker Thread. * @param isMonthly whether it is a monthly backup * @param doSendAppExit requests sending an application exit command when done * @return true if the prefs are set up and there were no errors before the SwingWorker thread was started *//*w w w . j a va 2s . com*/ private boolean doBackUp(final boolean isMonthly, final boolean doSendAppExit, final PropertyChangeListener propChgListener) { AppPreferences remotePrefs = AppPreferences.getLocalPrefs(); final String mysqldumpLoc = remotePrefs.get(MYSQLDUMP_LOC, getDefaultMySQLDumpLoc()); final String backupLoc = remotePrefs.get(MYSQLBCK_LOC, getDefaultBackupLoc()); if (!(new File(mysqldumpLoc)).exists()) { UIRegistry.showLocalizedError("MySQLBackupService.MYSQL_NO_DUMP", mysqldumpLoc); if (propChgListener != null) { propChgListener.propertyChange(new PropertyChangeEvent(MySQLBackupService.this, ERROR, 0, 1)); } return false; } File backupDir = new File(backupLoc); if (!backupDir.exists()) { if (!backupDir.mkdir()) { UIRegistry.showLocalizedError("MySQLBackupService.MYSQL_NO_BK_DIR", backupDir.getAbsoluteFile()); if (propChgListener != null) { propChgListener.propertyChange(new PropertyChangeEvent(MySQLBackupService.this, ERROR, 0, 1)); } return false; } } errorMsg = null; final String databaseName = DBConnection.getInstance().getDatabaseName(); getNumberofTables(); SwingWorker<Integer, Integer> backupWorker = new SwingWorker<Integer, Integer>() { protected String fullPath = null; /* (non-Javadoc) * @see javax.swing.SwingWorker#doInBackground() */ @Override protected Integer doInBackground() throws Exception { FileOutputStream backupOut = null; try { Thread.sleep(100); // Create output file SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_kk_mm_ss"); String fileName = sdf.format(Calendar.getInstance().getTime()) + (isMonthly ? "_monthly" : "") + ".sql"; fullPath = backupLoc + File.separator + fileName; File file = new File(fullPath); backupOut = new FileOutputStream(file); writeStats(getCollectionStats(getTableNames()), getStatsName(fullPath)); String userName = DBConnection.getInstance().getUserName(); String password = DBConnection.getInstance().getPassword(); if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) { Pair<String, String> up = UserAndMasterPasswordMgr.getInstance().getUserNamePasswordForDB(); if (up != null && up.first != null && up.second != null) { userName = up.first; password = up.second; } } String port = DatabaseDriverInfo.getDriver(DBConnection.getInstance().getDriverName()) .getPort(); String server = DBConnection.getInstance().getServerName(); Vector<String> args = new Vector<String>(); args.add(mysqldumpLoc); args.add("--user=" + userName); args.add("--password=" + password); args.add("--host=" + server); if (port != null) { args.add("--port=" + port); } args.add(databaseName); Process process = Runtime.getRuntime().exec(args.toArray(new String[0])); InputStream input = process.getInputStream(); byte[] bytes = new byte[8192 * 2]; double oneMeg = (1024.0 * 1024.0); long dspMegs = 0; long totalBytes = 0; do { int numBytes = input.read(bytes, 0, bytes.length); totalBytes += numBytes; if (numBytes > 0) { long megs = (long) (totalBytes / oneMeg); if (megs != dspMegs) { dspMegs = megs; long megsWithTenths = (long) ((totalBytes * 10.0) / oneMeg); firePropertyChange(MEGS, 0, megsWithTenths); } backupOut.write(bytes, 0, numBytes); } else { break; } } while (true); StringBuilder sb = new StringBuilder(); String line; BufferedReader errIn = new BufferedReader(new InputStreamReader(process.getErrorStream())); while ((line = errIn.readLine()) != null) { //System.err.println(line); if (line.startsWith("ERR") || StringUtils.contains(line, "Got error")) { sb.append(line); sb.append("\n"); if (StringUtils.contains(line, "1044") && StringUtils.contains(line, "LOCK TABLES")) { sb.append("\n"); sb.append(UIRegistry.getResourceString("MySQLBackupService.LCK_TBL_ERR")); sb.append("\n"); } } } errorMsg = sb.toString(); } catch (Exception ex) { ex.printStackTrace(); errorMsg = ex.toString(); UIRegistry.showLocalizedError("MySQLBackupService.EXCP_BK"); } finally { if (backupOut != null) { try { backupOut.flush(); backupOut.close(); } catch (IOException ex) { ex.printStackTrace(); errorMsg = ex.toString(); } } } return null; } @Override protected void done() { super.done(); UIRegistry.getStatusBar().setProgressDone(STATUSBAR_NAME); UIRegistry.clearSimpleGlassPaneMsg(); if (StringUtils.isNotEmpty(errorMsg)) { UIRegistry.showError(errorMsg); } if (doSendAppExit) { CommandDispatcher.dispatch(new CommandAction("App", "AppReqExit")); } if (propChgListener != null) { propChgListener .propertyChange(new PropertyChangeEvent(MySQLBackupService.this, DONE, null, fullPath)); } } }; final JStatusBar statusBar = UIRegistry.getStatusBar(); statusBar.setIndeterminate(STATUSBAR_NAME, true); UIRegistry.writeSimpleGlassPaneMsg(getLocalizedMessage("MySQLBackupService.BACKINGUP", databaseName), 24); backupWorker.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent evt) { if (MEGS.equals(evt.getPropertyName())) { long value = (Long) evt.getNewValue(); double val = value / 10.0; statusBar.setText(UIRegistry.getLocalizedMessage("MySQLBackupService.BACKUP_MEGS", val)); } } }); backupWorker.execute(); return true; }
From source file:edu.ku.brc.specify.config.FixAttachments.java
/** * // w w w . j a va 2 s .c o m */ public void checkForBadAttachments() { int count = getNumberofBadAttachments(); if (count == 0) { AppPreferences.getGlobalPrefs().putBoolean("CHECK_ATTCH_ERR", false); return; } URL url = null; JEditorPane htmlPane; try { url = new URL("http://files.specifysoftware.org/attachment_recovery.html"); htmlPane = new JEditorPane(url); } catch (Exception e) { e.printStackTrace(); htmlPane = new JEditorPane("text/html", //$NON-NLS-1$ "<html><body><h1>Network Error - You must have a network conneciton to get the instructions.</H1></body>"); } JScrollPane scrollPane = UIHelper.createScrollPane(htmlPane); htmlPane.setEditable(false); JPanel panel = new JPanel(new BorderLayout()); panel.add(scrollPane, BorderLayout.CENTER); panel.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6)); CustomDialog infoDlg = new CustomDialog((Dialog) null, "Recovery Information", true, CustomDialog.OKCANCEL, panel); infoDlg.setCancelLabel("Close"); infoDlg.setOkLabel("Print in Browser"); infoDlg.createUI(); infoDlg.setSize(1024, 600); try { hookupAction(infoDlg.getOkBtn(), url != null ? url.toURI() : null); infoDlg.setVisible(true); } catch (Exception ex) { } final String CNT = "CNT"; final SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() { int totalFiles = 0; HashMap<Integer, Vector<Object[]>> resultsHashMap = new HashMap<Integer, Vector<Object[]>>(); HashMap<Integer, String> tblTypeHash = new HashMap<Integer, String>(); HashMap<Integer, String> agentHash = new HashMap<Integer, String>(); HashMap<Integer, AttchTableModel> tableHash = new HashMap<Integer, AttchTableModel>(); ArrayList<JTable> tableList = new ArrayList<JTable>(); ArrayList<Integer> tableIdList = new ArrayList<Integer>(); @Override protected Integer doInBackground() throws Exception { DataProviderSessionIFace session = null; try { // This doesn't need to include the new attachments int[] tableIds = { AccessionAttachment.getClassTableId(), AgentAttachment.getClassTableId(), CollectingEventAttachment.getClassTableId(), CollectionObjectAttachment.getClassTableId(), ConservDescriptionAttachment.getClassTableId(), ConservEventAttachment.getClassTableId(), DNASequencingRunAttachment.getClassTableId(), FieldNotebookAttachment.getClassTableId(), FieldNotebookPageAttachment.getClassTableId(), FieldNotebookPageSetAttachment.getClassTableId(), LoanAttachment.getClassTableId(), LocalityAttachment.getClassTableId(), PermitAttachment.getClassTableId(), PreparationAttachment.getClassTableId(), RepositoryAgreementAttachment.getClassTableId(), TaxonAttachment.getClassTableId() }; Agent userAgent = AppContextMgr.getInstance().getClassObject(Agent.class); int totFiles = 0; firePropertyChange(CNT, 0, 0); int cnt = 0; for (int tableId : tableIds) { Vector<Object[]> results = getImageData(userAgent.getId(), tableId, tblTypeHash); if (results != null && results.size() > 0) { resultsHashMap.put(tableId, results); totFiles += results.size(); //System.out.println(tableId+" -> "+results.size()); } firePropertyChange(CNT, 0, (int) ((double) cnt / (double) tableIds.length * 100.0)); cnt++; } if (resultsHashMap.size() == 0) // Shouldn't happen { return null; } session = DataProviderFactory.getInstance().createSession(); firePropertyChange(CNT, 0, 0); int i = 1; for (int tblId : resultsHashMap.keySet()) { DBTableInfo ti = DBTableIdMgr.getInstance().getInfoById(tblId); Vector<Object[]> dataRows = new Vector<Object[]>(); Vector<Object[]> results = resultsHashMap.get(tblId); for (Object[] row : results) { Integer agentId = (Integer) row[3]; String userName = agentHash.get(agentId); if (userName == null) { userName = BasicSQLUtils.querySingleObj( "SELECT su.Name FROM agent a INNER JOIN specifyuser su ON a.SpecifyUserID = su.SpecifyUserID WHERE a.AgentID = " + row[3]); agentHash.put(agentId, userName); } //userName = i == 1 ? "bill.johnson" : "joe.smith"; int attachJoinID = (Integer) row[4]; String identTitle = getIdentityTitle(session, ti, attachJoinID); String fullPath = (String) row[2]; //fullPath = StringUtils.replace(fullPath, "darwin\\", "darwin2\\"); //boolean doesExist = (new File(fullPath)).exists() && i != 1; boolean doesExist = (new File(fullPath)).exists(); //String str = i != 1 ? "/Users/joe/Desktop/xxx.png" : "/Users/bill/Desktop/xxx.png"; //String fullPath = FilenameUtils.getFullPath(str) + String.format("DSC_%05d.png", i); Object[] rowObjs = new Object[8]; rowObjs[0] = StringUtils.isEmpty(identTitle) ? "" : (identTitle.length() > 30 ? identTitle.substring(0, 30) + "..." : identTitle); rowObjs[1] = FilenameUtils.getName(fullPath); rowObjs[2] = fullPath; rowObjs[3] = userName; rowObjs[4] = doesExist; rowObjs[5] = Boolean.FALSE; rowObjs[6] = row[0]; rowObjs[7] = attachJoinID; dataRows.add(rowObjs); if (doesExist) { totalFiles++; } firePropertyChange(CNT, 0, (int) ((double) i / (double) totFiles * 100.0)); i++; } AttchTableModel model = new AttchTableModel(dataRows); JTable table = new JTable(model); tableHash.put(tblId, model); tableList.add(table); tableIdList.add(tblId); } } catch (Exception ex) { ex.printStackTrace(); } finally { session.close(); } return null; } @Override protected void done() { UIRegistry.clearSimpleGlassPaneMsg(); if (tableList.size() > 0) { displayBadAttachments(tableList, tableIdList, resultsHashMap, tblTypeHash, tableHash, totalFiles); } super.done(); } }; final SimpleGlassPane glassPane = UIRegistry .writeSimpleGlassPaneMsg("Verifying attachments in the repository...", 24); glassPane.setProgress(0); worker.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent evt) { if (CNT.equals(evt.getPropertyName())) { glassPane.setProgress((Integer) evt.getNewValue()); } } }); worker.execute(); }
From source file:edu.ku.brc.specify.tasks.subpane.VisualQueryPanel.java
/** * @throws IOException /*from www . ja v a2 s. com*/ * */ private void doSearch() throws IOException { final String CNT = "CNT"; UIFieldFormatterIFace fieldFmt = null; if (typeCBX.getSelectedIndex() == 0) { fieldFmt = DBTableIdMgr.getFieldFormatterFor(CollectionObject.class, "catalogNumber"); } final StringBuilder pmStr = new StringBuilder(); final String placeMark = " <Placemark><name>%s - %d / %d</name><Point><coordinates>%8.5f, %8.5f, 5</coordinates></Point></Placemark>\n"; polySB.setLength(0); boxSB.setLength(0); final JStatusBar statusBar = UIRegistry.getStatusBar(); final UIFieldFormatterIFace fldFmt = fieldFmt; SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() { @Override protected Integer doInBackground() throws Exception { // fills pntList from polyline // polyline was filled via clicks on WorldWind totalNumRecords = BasicSQLUtils.getCountAsInt(buildSQL(true)); availPoints.clear(); model = (DefaultListModel) dbObjList.getModel(); model.removeAllElements(); topIdHash.clear(); markers.clear(); polygon = new Polyline(polyline.getPositions()); polygon.setClosed(true); for (Position p : polyline.getPositions()) { polySB.append(String.format(" %8.5f, %8.5f, 20\n", p.longitude.degrees, p.latitude.degrees)); } int maxThreshold = 1000; int index = 0; Connection conn = null; Statement stmt = null; try { conn = DBConnection.getInstance().createConnection(); stmt = conn.createStatement(); int currCnt = 0; ResultSet rs = stmt.executeQuery(buildSQL(false)); while (rs.next()) { if (currCnt < maxThreshold) { double lat = rs.getBigDecimal(2).doubleValue(); double lon = rs.getBigDecimal(3).doubleValue(); Position pos = Position.fromDegrees(lat, lon, 0.0); // ZZZ // if (GeometryMath.isLocationInside(pos, polygon.getPositions())) // { // LatLonPoint llp = new LatLonPoint(rs.getInt(1), lat, lon); // String title = rs.getString(4); // if (title != null) // { // title = (fldFmt != null ? fldFmt.formatToUI(title) :title).toString(); // } else // { // title = "N/A"; // } // llp.setTitle(title); // llp.setIndex(index++); // availPoints.add(llp); // markers.add(llp); // topIdHash.add(llp.getLocId()); // System.out.println(index+" / "+currCnt+" In: "+lat+", "+lon); // pmStr.append(String.format(placeMark, "In: ",index, currCnt, lon, lat)); // // } else // { // System.out.println(index+" / "+currCnt+" Tossing: "+lat+", "+lon); // pmStr.append(String.format(placeMark, "Tossing: ", index, currCnt, lon, lat)); // } } currCnt++; if (currCnt % 100 == 0) { firePropertyChange(CNT, 0, currCnt); } } rs.close(); } catch (SQLException ex) { ex.printStackTrace(); /*UsageTracker.incrSQLUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(BaseTreeTask.class, ex); log.error("SQLException: " + ex.toString()); //$NON-NLS-1$ lo .error(ex.getMessage());*/ } finally { try { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(BaseTreeTask.class, ex); ex.printStackTrace(); } } return null; } /* (non-Javadoc) * @see javax.swing.SwingWorker#done() */ @Override protected void done() { super.done(); if (doDebug) { try { final String template = FileUtils.readFileToString(new File("template.kml")); final PrintWriter pw = new PrintWriter(new File("debug.kml")); String str = StringUtils.replace(template, "<!-- BOX -->", boxSB.toString()); str = StringUtils.replace(str, "<!-- POLYGON -->", polySB.toString()); str = StringUtils.replace(str, "<!-- PLACEMARKS -->", pmStr.toString()); pw.println(str); pw.flush(); pw.close(); } catch (IOException ex) { } } UIRegistry.clearSimpleGlassPaneMsg(); statusBar.setProgressDone(STATUSBAR_NAME); for (LatLonPlacemarkIFace llp : markers) { model.addElement(llp); } if (markers.size() > 0) { wwPanel.placeMarkers(markers, null); searchBtn.setEnabled(false); } else { doClearAll(true); startBtn.setEnabled(false); } clearAllBtn.setEnabled(true); clearSearchBtn.setEnabled(true); } }; statusBar.setIndeterminate(STATUSBAR_NAME, false); statusBar.setProgressRange(STATUSBAR_NAME, 0, 100); final SimpleGlassPane glassPane = UIRegistry .writeSimpleGlassPaneMsg(getLocalizedMessage("MySQLBackupService.BACKINGUP", "XXX"), 24); worker.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent evt) { if (CNT.equals(evt.getPropertyName())) { int value = (Integer) evt.getNewValue(); int progress = (int) (((double) value / (double) totalNumRecords) * 100.0); glassPane.setProgress(progress); statusBar.setValue(STATUSBAR_NAME, progress); } } }); worker.execute(); }
From source file:edu.ku.brc.specify.config.init.DatabasePanel.java
/** * // w ww . j av a 2 s. co m */ public void createDB() { getValues(properties); final String databaseName = dbNameTxt.getText(); final String dbUserName = usernameTxt.getText(); final String dbPwd = passwordTxt.getText(); final String hostName = hostNameTxt.getText(); if (UIRegistry.isMobile()) { DBConnection.clearMobileMachineDir(); File tmpDir = DBConnection.getMobileMachineDir(databaseName); UIRegistry.setEmbeddedDBPath(tmpDir.getAbsolutePath()); } final DatabaseDriverInfo driverInfo = (DatabaseDriverInfo) drivers.getSelectedItem(); String connStrInitial = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open, hostName, databaseName, dbUserName, dbPwd, driverInfo.getName()); //System.err.println(connStrInitial); DBConnection.checkForEmbeddedDir(connStrInitial); DBConnection.getInstance().setDriverName(driverInfo.getName()); DBConnection.getInstance().setServerName(hostName); VerifyStatus status = verifyDatabase(properties); if ((isOK == null || !isOK) && status == VerifyStatus.OK) { progressBar.setIndeterminate(true); progressBar.setVisible(true); label.setText(getResourceString("CONN_DB")); createDBBtn.setVisible(false); setUIEnabled(false); DatabasePanel.this.label.setForeground(Color.BLACK); SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() { @Override protected Object doInBackground() throws Exception { isOK = false; DBMSUserMgr mgr = DBMSUserMgr.getInstance(); List<PermissionInfo> perms = null; boolean dbmsOK = false; if (driverInfo.isEmbedded()) { if (checkForProcesses) { ProcessListUtil.checkForMySQLProcesses(null); checkForProcesses = false; } if (UIRegistry.isMobile()) { File mobileTmpDir = DBConnection.getMobileMachineDir(); if (!mobileTmpDir.exists()) { if (!mobileTmpDir.mkdirs()) { System.err.println( "Dir[" + mobileTmpDir.getAbsolutePath() + "] didn't get created!"); // throw exception } DBConnection.setCopiedToMachineDisk(true); } } String newConnStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open, hostName, databaseName, dbUserName, dbPwd, driverInfo.getName()); if (driverInfo.isEmbedded()) { //System.err.println(newConnStr); try { Class.forName(driverInfo.getDriverClassName()); // This call will create the database if it doesn't exist DBConnection testDB = DBConnection.createInstance(driverInfo.getDriverClassName(), driverInfo.getDialectClassName(), databaseName, newConnStr, dbUserName, dbPwd); testDB.getConnection(); // Opens the connection if (testDB != null) { testDB.close(); } dbmsOK = true; } catch (Exception ex) { ex.printStackTrace(); } DBConnection.getInstance().setDatabaseName(null); } } else if (mgr.connectToDBMS(dbUserName, dbPwd, hostName)) { perms = mgr.getPermissionsForCurrentUser(); Pair<List<PermissionInfo>, List<PermissionInfo>> missingPerms = PermissionInfo .getMissingPerms(perms, createDBPerms, databaseName); if (missingPerms.getFirst().size() > 0) { final String missingPermStr = PermissionInfo.getMissingPermissionString(mgr, missingPerms.getFirst(), databaseName); SwingUtilities.invokeLater(new Runnable() { /* (non-Javadoc) * @see java.lang.Runnable#run() */ @Override public void run() { UIRegistry.showLocalizedError("SEC_MISSING_PERMS", dbUserName, missingPermStr); } }); dbmsOK = false; } else { dbmsOK = true; } mgr.close(); } if (dbmsOK) { properties.put(DB_SKIP_CREATE, false); if (perms != null) { properties.put(DBUSERPERMS, perms); } firePropertyChange(PROPNAME, 0, 1); try { SpecifySchemaGenerator.generateSchema(driverInfo, hostName, databaseName, dbUserName, dbPwd); // false means create new database, true means update String connStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Create, hostName, databaseName); if (connStr == null) { connStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open, hostName, databaseName); } firePropertyChange(PROPNAME, 0, 2); // tryLogin sets up DBConnection if (UIHelper.tryLogin(driverInfo.getDriverClassName(), driverInfo.getDialectClassName(), dbNameTxt.getText(), connStr, dbUserName, dbPwd)) { if (!checkEngineCharSet(properties)) { return false; } isOK = true; firePropertyChange(PROPNAME, 0, 3); Thumbnailer thumb = Thumbnailer.getInstance(); File thumbFile = XMLHelper.getConfigDir("thumbnail_generators.xml"); thumb.registerThumbnailers(thumbFile); thumb.setQuality(0.5f); thumb.setMaxSize(128, 128); File attLoc = UIRegistry.getAppDataSubDir("AttachmentStorage", true); AttachmentManagerIface attachMgr = new FileStoreAttachmentManager(attLoc); AttachmentUtils.setAttachmentManager(attachMgr); AttachmentUtils.setThumbnailer(thumb); } else { errorKey = "NO_LOGIN_ROOT"; } } catch (Exception ex) { errorKey = "DB_UNRECOVERABLE"; } } else { errorKey = "NO_CONN_ROOT"; mgr.close(); } return null; } /* (non-Javadoc) * @see javax.swing.SwingWorker#done() */ @Override protected void done() { super.done(); setUIEnabled(true); progressBar.setIndeterminate(false); progressBar.setVisible(false); updateBtnUI(); createDBBtn.setVisible(!isOK); if (isOK) { label.setText(UIRegistry.getResourceString("DB_CREATED")); setUIEnabled(false); } else { label.setText(UIRegistry.getResourceString(errorKey != null ? errorKey : "ERR_CRE_DB")); UIRegistry.showLocalizedError(errorKey != null ? errorKey : "ERR_CRE_DB"); } } }; worker.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent evt) { if (PROPNAME.equals(evt.getPropertyName())) { String key = null; switch ((Integer) evt.getNewValue()) { case 1: key = "BLD_SCHEMA"; break; case 2: key = "DB_FRST_LOGIN"; break; case 3: key = "BLD_CACHE"; break; default: break; } if (key != null) { DatabasePanel.this.label.setText(UIRegistry.getResourceString(key)); } } } }); worker.execute(); } else if (status == VerifyStatus.ERROR) { errorKey = "NO_LOGIN_ROOT"; DatabasePanel.this.label.setText(UIRegistry.getResourceString(errorKey)); DatabasePanel.this.label.setForeground(Color.RED); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { UIRegistry.getTopWindow().pack(); } }); } }
From source file:edu.ku.brc.specify.datamodel.busrules.CollectionObjectBusRules.java
/** * //from w w w .j a v a 2 s .c o m */ public void doCreateBatchOfColObj(final Pair<String, String> catNumPair) { if (catNumPair.getFirst().equals(catNumPair.getSecond())) { return; } DBFieldInfo CatNumFld = DBTableIdMgr.getInstance().getInfoById(CollectionObject.getClassTableId()) .getFieldByColumnName("CatalogNumber"); final UIFieldFormatterIFace formatter = CatNumFld.getFormatter(); if (!formatter.isIncrementer()) { //XXX this will have been checked earlier, right? UIRegistry.showLocalizedError(NonIncrementingCatNum); return; } final Vector<String> nums = new Vector<String>(); processBatchContents(catNumPair, false, false, nums); SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() { private Vector<Pair<Integer, String>> objectsAdded = new Vector<Pair<Integer, String>>(); private Vector<String> objectsNotAdded = new Vector<String>(); private RecordSet batchRS; //private boolean invalidEntry = false; /* (non-Javadoc) * @see javax.swing.SwingWorker#doInBackground() */ @Override protected Integer doInBackground() throws Exception { String catNum = catNumPair.getFirst(); Integer collId = AppContextMgr.getInstance().getClassObject(Collection.class).getId(); String coIdSql = "select CollectionObjectID from collectionobject where CollectionMemberID = " + collId + " and CatalogNumber = '"; objectsAdded.add(new Pair<Integer, String>( (Integer) BasicSQLUtils.querySingleObj(coIdSql + catNum + "'"), catNum)); int cnt = 0; CollectionObject co = null; //CollectionObject carryForwardCo = (CollectionObject )formViewObj.getDataObj(); CollectionObject carryForwardCo; DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession(); try { carryForwardCo = session.get(CollectionObject.class, ((CollectionObject) formViewObj.getDataObj()).getId()); } finally { session.close(); } Thread.sleep(666); //Perhaps this is unnecessary, but it seems //to prevent sporadic "illegal access to loading collection" hibernate errors. try { for (String currentCat : nums) { try { co = new CollectionObject(); co.initialize(); //Collection doesn't get set in co.initialize(), or carryForward, but it needs to be set. co.setCollection(AppContextMgr.getInstance().getClassObject(Collection.class)); //ditto, but doesn't so much need to be set co.setModifiedByAgent(carryForwardCo.getModifiedByAgent()); co.setCatalogNumber(currentCat); formViewObj.setNewObject(co); if (formViewObj.saveObject()) { objectsAdded.add(new Pair<Integer, String>( (Integer) BasicSQLUtils .querySingleObj(coIdSql + co.getCatalogNumber() + "'"), co.getCatalogNumber())); } else { objectsNotAdded.add(formatter.formatToUI(co.getCatalogNumber()).toString()); } } catch (Exception ex) { log.error(ex); objectsNotAdded.add(formatter.formatToUI(currentCat) + ": " + (ex.getLocalizedMessage() == null ? "" : ex.getLocalizedMessage())); } cnt++; firePropertyChange(GLASSKEY, 0, cnt); } firePropertyChange(GLASSKEY, 0, nums.size()); } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(Uploader.class, ex); } formViewObj.setDataObj(carryForwardCo); saveBatchObjectsToRS(); return objectsAdded.size(); } /** * Save the objects added to a Recordset */ protected void saveBatchObjectsToRS() { batchRS = new RecordSet(); batchRS.initialize(); batchRS.setDbTableId(CollectionObject.getClassTableId()); String name = getResourceString(BatchRSBaseName) + " " + formatter.formatToUI(catNumPair.getFirst()) + "-" + formatter.formatToUI(catNumPair.getSecond()); if (objectsNotAdded.size() > 0) { name += "-" + UIRegistry.getResourceString(IncompleteSaveFlag); } batchRS.setName(name); for (Pair<Integer, String> obj : objectsAdded) { batchRS.addItem(obj.getFirst()); } DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession(); boolean transOpen = false; try { BusinessRulesIFace busRule = DBTableIdMgr.getInstance().getBusinessRule(RecordSet.class); if (busRule != null) { busRule.beforeSave(batchRS, session); } batchRS.setTimestampCreated(new Timestamp(System.currentTimeMillis())); batchRS.setOwner(AppContextMgr.getInstance().getClassObject(SpecifyUser.class)); session.beginTransaction(); transOpen = true; session.save(batchRS); if (busRule != null) { if (!busRule.beforeSaveCommit(batchRS, session)) { session.rollback(); throw new Exception("Business rules processing failed"); } } session.commit(); transOpen = false; if (busRule != null) { busRule.afterSaveCommit(batchRS, session); } } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(Uploader.class, ex); if (transOpen) { session.rollback(); } } } /** * Add the batch RS to the RecordSetTask UI */ protected void addBatchRSToUI() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { CommandAction cmd = new CommandAction(RecordSetTask.RECORD_SET, RecordSetTask.ADD_TO_NAV_BOX); cmd.setData(batchRS); CommandDispatcher.dispatch(cmd); } }); } /* (non-Javadoc) * @see javax.swing.SwingWorker#done() */ @Override protected void done() { super.done(); processingSeries.set(false); addBatchRSToUI(); UIRegistry.clearSimpleGlassPaneMsg(); if (objectsNotAdded.size() == 0) { UIRegistry.displayLocalizedStatusBarText(BatchSaveSuccess, formatter.formatToUI(catNumPair.getFirst()), formatter.formatToUI(catNumPair.getSecond())); } else { showBatchErrorObjects(objectsNotAdded, BatchSaveErrorsTitle, BatchSaveErrors); } } }; final SimpleGlassPane gp = UIRegistry.writeSimpleGlassPaneMsg(getI10N("SAVING_BATCH"), 24); gp.setProgress(0); worker.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent evt) { if (GLASSKEY.equals(evt.getPropertyName())) { double value = (double) ((Integer) evt.getNewValue()).intValue(); int percent = (int) (value / ((double) nums.size()) * 100.0); gp.setProgress(percent); } } }); processingSeries.set(true); worker.execute(); // try { // worker.get(); // } catch (Exception ex) { // ex.printStackTrace(); // } }
From source file:com.marginallyclever.makelangelo.MainGUI.java
protected boolean LoadDXF(String filename) { if (ChooseImageConversionOptions(true) == false) return false; // where to save temp output file? final String destinationFile = GetTempDestinationFile(); final String srcFile = filename; TabToLog();// w w w .j a va 2 s . c o m final ProgressMonitor pm = new ProgressMonitor(null, translator.get("Converting"), "", 0, 100); pm.setProgress(0); pm.setMillisToPopup(0); final SwingWorker<Void, Void> s = new SwingWorker<Void, Void>() { public boolean ok = false; @SuppressWarnings("unchecked") @Override public Void doInBackground() { Log("<font color='green'>" + translator.get("Converting") + " " + destinationFile + "</font>\n"); Parser parser = ParserBuilder.createDefaultParser(); double dxf_x2 = 0; double dxf_y2 = 0; OutputStreamWriter out = null; try { out = new OutputStreamWriter(new FileOutputStream(destinationFile), "UTF-8"); DrawingTool tool = machineConfiguration.GetCurrentTool(); out.write(machineConfiguration.GetConfigLine() + ";\n"); out.write(machineConfiguration.GetBobbinLine() + ";\n"); out.write("G00 G90;\n"); tool.WriteChangeTo(out); tool.WriteOff(out); parser.parse(srcFile, DXFParser.DEFAULT_ENCODING); DXFDocument doc = parser.getDocument(); Bounds b = doc.getBounds(); double width = b.getMaximumX() - b.getMinimumX(); double height = b.getMaximumY() - b.getMinimumY(); double cx = (b.getMaximumX() + b.getMinimumX()) / 2.0f; double cy = (b.getMaximumY() + b.getMinimumY()) / 2.0f; double sy = machineConfiguration.GetPaperHeight() * 10 / height; double sx = machineConfiguration.GetPaperWidth() * 10 / width; double scale = (sx < sy ? sx : sy) * machineConfiguration.paper_margin; sx = scale * (machineConfiguration.reverseForGlass ? -1 : 1); // count all entities in all layers Iterator<DXFLayer> layer_iter = (Iterator<DXFLayer>) doc.getDXFLayerIterator(); int entity_total = 0; int entity_count = 0; while (layer_iter.hasNext()) { DXFLayer layer = (DXFLayer) layer_iter.next(); Log("<font color='yellow'>Found layer " + layer.getName() + "</font>\n"); Iterator<String> entity_iter = (Iterator<String>) layer.getDXFEntityTypeIterator(); while (entity_iter.hasNext()) { String entity_type = (String) entity_iter.next(); List<DXFEntity> entity_list = (List<DXFEntity>) layer.getDXFEntities(entity_type); Log("<font color='yellow'>+ Found " + entity_list.size() + " of type " + entity_type + "</font>\n"); entity_total += entity_list.size(); } } // set the progress meter pm.setMinimum(0); pm.setMaximum(entity_total); // convert each entity layer_iter = doc.getDXFLayerIterator(); while (layer_iter.hasNext()) { DXFLayer layer = (DXFLayer) layer_iter.next(); Iterator<String> entity_type_iter = (Iterator<String>) layer.getDXFEntityTypeIterator(); while (entity_type_iter.hasNext()) { String entity_type = (String) entity_type_iter.next(); List<DXFEntity> entity_list = layer.getDXFEntities(entity_type); if (entity_type.equals(DXFConstants.ENTITY_TYPE_LINE)) { for (int i = 0; i < entity_list.size(); ++i) { pm.setProgress(entity_count++); DXFLine entity = (DXFLine) entity_list.get(i); Point start = entity.getStartPoint(); Point end = entity.getEndPoint(); double x = (start.getX() - cx) * sx; double y = (start.getY() - cy) * sy; double x2 = (end.getX() - cx) * sx; double y2 = (end.getY() - cy) * sy; // is it worth drawing this line? double dx = x2 - x; double dy = y2 - y; if (dx * dx + dy * dy < tool.GetDiameter() / 2.0) { continue; } dx = dxf_x2 - x; dy = dxf_y2 - y; if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) { if (tool.DrawIsOn()) { tool.WriteOff(out); } tool.WriteMoveTo(out, (float) x, (float) y); } if (tool.DrawIsOff()) { tool.WriteOn(out); } tool.WriteMoveTo(out, (float) x2, (float) y2); dxf_x2 = x2; dxf_y2 = y2; } } else if (entity_type.equals(DXFConstants.ENTITY_TYPE_SPLINE)) { for (int i = 0; i < entity_list.size(); ++i) { pm.setProgress(entity_count++); DXFSpline entity = (DXFSpline) entity_list.get(i); entity.setLineWeight(30); DXFPolyline polyLine = DXFSplineConverter.toDXFPolyline(entity); boolean first = true; for (int j = 0; j < polyLine.getVertexCount(); ++j) { DXFVertex v = polyLine.getVertex(j); double x = (v.getX() - cx) * sx; double y = (v.getY() - cy) * sy; double dx = dxf_x2 - x; double dy = dxf_y2 - y; if (first == true) { first = false; if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) { // line does not start at last tool location, lift and move. if (tool.DrawIsOn()) { tool.WriteOff(out); } tool.WriteMoveTo(out, (float) x, (float) y); } // else line starts right here, do nothing. } else { // not the first point, draw. if (tool.DrawIsOff()) tool.WriteOn(out); if (j < polyLine.getVertexCount() - 1 && dx * dx + dy * dy < tool.GetDiameter() / 2.0) continue; // less than 1mm movement? Skip it. tool.WriteMoveTo(out, (float) x, (float) y); } dxf_x2 = x; dxf_y2 = y; } } } else if (entity_type.equals(DXFConstants.ENTITY_TYPE_POLYLINE)) { for (int i = 0; i < entity_list.size(); ++i) { pm.setProgress(entity_count++); DXFPolyline entity = (DXFPolyline) entity_list.get(i); boolean first = true; for (int j = 0; j < entity.getVertexCount(); ++j) { DXFVertex v = entity.getVertex(j); double x = (v.getX() - cx) * sx; double y = (v.getY() - cy) * sy; double dx = dxf_x2 - x; double dy = dxf_y2 - y; if (first == true) { first = false; if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) { // line does not start at last tool location, lift and move. if (tool.DrawIsOn()) { tool.WriteOff(out); } tool.WriteMoveTo(out, (float) x, (float) y); } // else line starts right here, do nothing. } else { // not the first point, draw. if (tool.DrawIsOff()) tool.WriteOn(out); if (j < entity.getVertexCount() - 1 && dx * dx + dy * dy < tool.GetDiameter() / 2.0) continue; // less than 1mm movement? Skip it. tool.WriteMoveTo(out, (float) x, (float) y); } dxf_x2 = x; dxf_y2 = y; } } } } } // entities finished. Close up file. tool.WriteOff(out); tool.WriteMoveTo(out, 0, 0); ok = true; } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (out != null) out.close(); } catch (IOException e) { e.printStackTrace(); } } pm.setProgress(100); return null; } @Override public void done() { pm.close(); Log("<font color='green'>" + translator.get("Finished") + "</font>\n"); PlayConversionFinishedSound(); if (ok) { LoadGCode(destinationFile); TabToDraw(); } Halt(); } }; s.addPropertyChangeListener(new PropertyChangeListener() { // Invoked when task's progress property changes. public void propertyChange(PropertyChangeEvent evt) { if ("progress" == evt.getPropertyName()) { int progress = (Integer) evt.getNewValue(); pm.setProgress(progress); String message = String.format("%d%%\n", progress); pm.setNote(message); if (s.isDone()) { Log("<font color='green'>" + translator.get("Finished") + "</font>\n"); } else if (s.isCancelled() || pm.isCanceled()) { if (pm.isCanceled()) { s.cancel(true); } Log("<font color='green'>" + translator.get("Cancelled") + "</font>\n"); } } } }); s.execute(); return true; }
From source file:pcgui.SetupParametersPanel.java
private void runModel() { //retrieve master configuration ArrayList<ArrayList<Object>> mod = model.getData(); //create a new list and check for dependencies ArrayList<Symbol> list = new ArrayList<Symbol>(); //independent variable list ArrayList<Symbol> ivList = new ArrayList<Symbol>(); //step variable list ArrayList<Symbol> stepList = new ArrayList<Symbol>(); //dependent list ArrayList<Symbol> depList = new ArrayList<Symbol>(); //output tracking ArrayList<Symbol> trackedSymbols = new ArrayList<Symbol>(); Symbol tempSym = null;//from w w w . ja v a 2 s .c o m //step variable counter to be used for making combinations int stepVarCount = 0; long stepCombinations = 1; TextParser textParser = new TextParser(); compileSuccess = true; for (ArrayList<Object> rowData : mod) { tempSym = paramList.get(mod.indexOf(rowData)); if ("Manual".equals((String) rowData.get(2))) { System.out.println("Found Customized Symbol : " + rowData.get(0)); System.out.println("Value : " + rowData.get(3) + ": type=" + rowData.get(3).getClass()); tempSym.mode = "Manual"; String data = (String) rowData.get(3); //checking dependent variables if (data != null && !data.isEmpty()) { //dependent if (hashTable.containsKey(data)) { tempSym.setDependent(true); depList.add(tempSym); } else { //independents tempSym.setDependent(false); tempSym.set(data); ivList.add(tempSym); } } } else if ("External".equals((String) rowData.get(2))) { System.out.println("Found External Symbol : " + rowData.get(0)); System.out.println("External : " + rowData.get(3) + ": type=" + rowData.get(3).getClass()); if (!(((String) rowData.get(4)).isEmpty())) { tempSym.externalFile = (String) rowData.get(4); tempSym.set(tempSym.externalFile); tempSym.mode = "External"; if (tempSym.externalFile.endsWith(".xls") || tempSym.externalFile.endsWith(".xlsx")) { if (tempSym.excelFileRange.isEmpty()) { // TODO show an error dialog System.err.println("Error user missed excel range arguments"); JOptionPane.showMessageDialog(new JFrame(), "Error user missed excel range arguments"); return; } else { tempSym.excelFileRange = (String) rowData.get(5); //'[Daten_10$B'+(i)+':B'+(5+n)+']' //user has to add quote before the 1st + and after the last + //the data file used should be inside Models/Data folder tempSym.set("Models//Data//" + tempSym.externalFile + "::" + tempSym.excelFileRange); } } else { //for non excel files tempSym.set("Models//Data//" + tempSym.externalFile); } } else { System.err.println("Error user missed excel file"); JOptionPane.showMessageDialog(new JFrame(), "Please enter external file for variable : " + tempSym.name); return; } ivList.add(tempSym); list.add(tempSym); } else if ("Randomized".equals((String) rowData.get(2))) { System.out.println("Found Randomized Symbol : " + rowData.get(0)); System.out.println("Value : " + rowData.get(6)); boolean isValid = textParser.validate((String) rowData.get(6)); if (isValid) { //saving the array declaration parameters if (((String) rowData.get(1)).trim().startsWith("array")) { System.out.println("Found randomized array : " + tempSym.name); //found an array tempSym.isArray = true; List<String> arrayParams = parseArrayParam((String) rowData.get(1)); tempSym.arrayParams = arrayParams; System.out.println("Param list : "); for (Object obj : tempSym.arrayParams) { //check if any of the param is symbol if (hashTable.containsKey((String) obj)) { tempSym.isDependentDimension = true; depList.add(tempSym); break; } System.out.println((String) obj); } //add to independent variable list if none of the dimension is based on variable if (!tempSym.isDependentDimension) { ivList.add(tempSym); } } Distribution dist = textParser.getDistribution((String) rowData.get(6)); if ("Step".equalsIgnoreCase(dist.getDistribution())) { System.err.println("Error: User entered step distribution in Randomized variable"); JOptionPane.showMessageDialog(new JFrame(), "Please enter random distribution only" + " for variable : " + tempSym.name); return; } tempSym.setDistribution(dist); tempSym.mode = "Randomized"; //check dependent variables List<String> distParamList = dist.getParamList(); for (String param : distParamList) { //TODO: if .contains work on Symbol if (hashTable.containsKey(param) && !depList.contains(tempSym)) { tempSym.setDependent(true); depList.add(tempSym); break; } } //generate apache distribution object for independent vars if (!tempSym.isDependent()) { Object apacheDist = generateDistribution(tempSym); tempSym.setApacheDist(apacheDist); if ("StepDistribution".equals(apacheDist.getClass().getSimpleName())) { stepVarCount++; StepDistribution stepDist = (StepDistribution) apacheDist; stepCombinations *= stepDist.getStepCount(); tempSym.isStepDist = true; tempSym.setStepDist(stepDist); stepList.add(tempSym); } else if (!ivList.contains(tempSym) && !tempSym.isDependentDimension) { ivList.add(tempSym); } } list.add(tempSym); } else { System.err.println("Error: User entered unknown distribution for randomized variable"); JOptionPane.showMessageDialog(new JFrame(), "Please enter random distribution only" + " for variable : " + tempSym.name); return; } } else if ("Step".equals((String) rowData.get(2))) { System.out.println("Found Step Symbol : " + rowData.get(0)); System.out.println("Value : " + rowData.get(6)); Distribution dist = textParser.getStepDistribution((String) rowData.get(6)); if (dist == null || !"Step".equalsIgnoreCase(dist.getDistribution())) { System.err.println("Error: User entered unknown distribution for step variable"); JOptionPane.showMessageDialog(new JFrame(), "Please enter random distribution only" + " for variable : " + tempSym.name); return; } boolean isValid = textParser.validateStepDist((String) rowData.get(6)); if (isValid) { //saving the array declaration parameters if (((String) rowData.get(1)).trim().startsWith("array")) { //TODO: if this can work for step arrays System.out.println("Found step array : " + tempSym.name); //found an array tempSym.isArray = true; List<String> arrayParams = parseArrayParam((String) rowData.get(1)); tempSym.arrayParams = arrayParams; System.out.println("Param list : "); for (Object obj : tempSym.arrayParams) { //check if any of the param is symbol if (hashTable.containsKey((String) obj)) { tempSym.isDependentDimension = true; depList.add(tempSym); break; } System.out.println((String) obj); } //add to independent variable list if none of the dimension is based on variable if (!tempSym.isDependentDimension) { ivList.add(tempSym); } } tempSym.setDistribution(dist); tempSym.mode = "Randomized"; //check dependent variables List<String> distParamList = dist.getParamList(); for (String param : distParamList) { if (hashTable.containsKey(param) && !depList.contains(tempSym)) { tempSym.setDependent(true); depList.add(tempSym); break; } } //generate apache distribution object for independent vars if (!tempSym.isDependent()) { Object apacheDist = generateDistribution(tempSym); tempSym.setApacheDist(apacheDist); //dual safe check if ("StepDistribution".equals(apacheDist.getClass().getSimpleName())) { stepVarCount++; StepDistribution stepDist = (StepDistribution) apacheDist; stepCombinations *= stepDist.getStepCount(); tempSym.isStepDist = true; tempSym.setStepDist(stepDist); stepList.add(tempSym); } else if (!ivList.contains(tempSym) && !tempSym.isDependentDimension) { ivList.add(tempSym); } } list.add(tempSym); } else { System.err.println("Error: User entered unknown distribution for randomized variable"); JOptionPane.showMessageDialog(new JFrame(), "Please enter random distribution only" + " for variable : " + tempSym.name); return; } } //add symbol to trackedSymbol list for output tracking if (tempSym != null && rowData.get(7) != null && (boolean) rowData.get(7)) { trackedSymbols.add(tempSym); } } System.out.println("Total step distribution variables =" + stepVarCount); System.out.println("Total step combinations =" + stepCombinations); System.out.println("====STEP VARIABLES===="); for (Symbol sym : stepList) { System.out.println(sym.name); } //resolve dependencies and generate random distributions object //list for an instance of execution HashMap<String, Integer> map = new HashMap<String, Integer>(); for (int i = 0; i < stepList.size(); i++) { map.put(stepList.get(i).name, getSteppingCount(stepList, i)); System.out.println(stepList.get(i).name + " has stepping count =" + map.get(stepList.get(i).name)); } int repeatitions = 0; try { repeatitions = Integer.parseInt(repeatCount.getText()); } catch (NumberFormatException e) { System.err.println("Invalid repeat count"); JOptionPane.showMessageDialog(new JFrame(), "Please enter integer value for repeat count"); return; } //generate instances showProgressBar(); final long totalIterations = repeatitions * stepCombinations; final long repeatitionsFinal = repeatitions; final long combinations = stepCombinations; SwingWorker<Void, Void> executionTask = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { long itNum = 1; int itCount = 1; System.out.println("Total iterations: " + totalIterations); // TODO Auto-generated method stub for (int c = 1; c <= repeatitionsFinal; c++) { for (int i = 1; i <= combinations; i++) { setProgress((int) (itNum * 100 / totalIterations)); //step variables first for (Symbol sym : stepList) { if (map.get(sym.name) == 1 || i % map.get(sym.name) - 1 == 0 || i == 1) { sym.set(sym.getStepDist().sample()); hashTable.put(sym.name, sym); } //System.out.println(sym.name+" = "+sym.get()); } //independent randomized variables for (Symbol sym : ivList) { if (sym.mode.equals("Randomized")) { Object distObj = sym.getApacheDist(); switch (sym.getApacheDist().getClass().getSimpleName()) { case "UniformIntegerDistribution": //case "GeometricDistribution" : // case "BinomialDistribution"://not implemented yet IntegerDistribution intDist = (IntegerDistribution) distObj; if (sym.isArray) { //generate Stringified array String val = generateIndependentArray(sym, intDist); sym.set(val); hashTable.put(sym.name, sym); } break; case "LogisticDistribution": case "UniformRealDistribution": case "ExponentialDistribution": case "GammaDistribution": case "NormalDistribution": RealDistribution realDist = (RealDistribution) distObj; if (sym.isArray) { //generate Stringified array String val = generateIndependentArray(sym, realDist); sym.set(val); hashTable.put(sym.name, sym); } break; default: System.err.println("Unknown distribution"); JOptionPane.showMessageDialog(new JFrame(), "Error occurred : Unknown distribution"); return null; } } //System.out.println(sym.name+" = "+sym.get()); //other types of independent variable already have values } for (Symbol sym : depList) { if (sym.mode != null && "Manual".equals(sym.mode)) { //value depends on some other value String ref = (String) sym.get(); Object val = (Object) hashTable.get(ref); sym.set(val); hashTable.put(sym.name, sym); } else if (sym.mode != null && "Randomized".equals(sym.mode)) { Object distObj = null; //when a random distribution depends on another variable Distribution dist = sym.getDistribution(); StringBuilder sb = new StringBuilder(); sb.append(dist.getDistribution()); sb.append("("); for (String s : dist.getParamList()) { //replacing a dependency by actual value of that variable if (hashTable.containsKey(s)) { Symbol val = (Symbol) hashTable.get(s); sb.append((String) val.get()); } else { //this param is a number itself sb.append(s); } sb.append(","); } //check if param list length = 0 if (dist.getParamList() != null && dist.getParamList().size() >= 1) { sb.deleteCharAt(sb.length() - 1); } sb.append(")"); if (sym.typeString != null && sym.typeString.contains("integer")) { try { distObj = textParser.parseText(sb.toString(), TextParser.INTEGER); sym.setApacheDist(distObj); } catch (Exception e) { System.err.println( "Exception occured when trying to get Random distribution for variable" + sym.name + "\n" + e.getMessage()); e.printStackTrace(); JOptionPane.showMessageDialog(new JFrame(), "Error occurred : " + e.getMessage()); return null; } } else { try { distObj = textParser.parseText(sb.toString(), TextParser.REAL); sym.setApacheDist(distObj); } catch (Exception e) { System.err.println( "Exception occured when trying to get Random distribution for variable" + sym.name + "\n" + e.getMessage()); e.printStackTrace(); JOptionPane.showMessageDialog(new JFrame(), "Error occurred : " + e.getMessage()); return null; } } //generation of actual apache distribution objects switch (distObj.getClass().getSimpleName()) { case "UniformIntegerDistribution": //case "GeometricDistribution" : //case "BinomialDistribution": IntegerDistribution intDist = (IntegerDistribution) distObj; if (sym.isArray) { //generate Stringified array String val = generateDependentArray(sym, intDist); sym.set(val); hashTable.put(sym.name, sym); } break; case "LogisticDistribution": case "UniformRealDistribution": case "ExponentialDistribution": case "GammaDistribution": case "NormalDistribution": RealDistribution realDist = (RealDistribution) distObj; if (sym.isArray) { //generate Stringified array String val = generateDependentArray(sym, realDist); sym.set(val); hashTable.put(sym.name, sym); } break; default: System.err.println("Unknown distribution"); JOptionPane.showMessageDialog(new JFrame(), "Error occurred : Unknown distribution"); } } //System.out.println(sym.name+" = "+sym.get()); } ArrayList<Symbol> instanceList = new ArrayList<Symbol>(); instanceList.addAll(stepList); instanceList.addAll(ivList); instanceList.addAll(depList); System.out.println("=======ITERATION " + itCount++ + "======="); System.out.println("=======instanceList.size =" + instanceList.size() + " ======="); for (Symbol sym : instanceList) { System.out.println(sym.name + " = " + sym.get()); } //runModel here try { //TODO anshul: pass output variables to be written to excel System.out.println("Tracked output symbols"); for (Symbol sym : trackedSymbols) { System.out.println(sym.name); } HashMap<String, OutputParams> l = parser.changeModel(instanceList, trackedSymbols, itNum); if (l == null) { compileSuccess = false; break; } } catch (/*XPRMCompileException | */XPRMLicenseError | IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(new JFrame(), "Error occurred : " + e.getMessage()); compileSuccess = false; break; } itNum++; } } this.notifyAll(); done(); return null; } @Override protected void done() { super.done(); //check if compilation was successful if (compileSuccess) { ModelSaver.saveModelResult(); visPanel.setTrackedVariables(trackedSymbols); mapVisPanel.setTrackedVariables(trackedSymbols); JOptionPane.showMessageDialog(new JFrame("Success"), "Model execution completed.\nOutput written to excel file : " + outputFile); } else { //Error popup should have been shown by ModelParser System.err.println("There was an error while running the model."); return; } if (progressFrame != null) { progressFrame.dispose(); } } }; executionTask.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if ("progress" == evt.getPropertyName()) { int progress = (Integer) evt.getNewValue(); if (pbar != null) pbar.setValue(progress); if (taskOutput != null) taskOutput.append(String.format("Completed %d%% of task.\n", executionTask.getProgress())); } } }); executionTask.execute(); }
From source file:richtercloud.document.scanner.gui.MainPanel.java
/** * Uses a modal dialog in order to display the progress of the retrieval and * make the operation cancelable./* w w w. ja v a 2 s . c o m*/ * @param documentFile * @return the retrieved images or {@code null} if the retrieval has been * canceled (in dialog) * @throws DocumentAddException * @throws InterruptedException * @throws ExecutionException */ /* internal implementation notes: - can't use ProgressMonitor without blocking EVT instead of a model dialog when using SwingWorker.get */ public List<BufferedImage> retrieveImages(final File documentFile) throws DocumentAddException, InterruptedException, ExecutionException { if (documentFile == null) { throw new IllegalArgumentException("documentFile mustn't be null"); } final SwingWorkerGetWaitDialog dialog = new SwingWorkerGetWaitDialog(SwingUtilities.getWindowAncestor(this), //owner DocumentScanner.generateApplicationWindowTitle("Wait", APP_NAME, APP_VERSION), //dialogTitle "Retrieving image data", //labelText null //progressBarText ); final SwingWorker<List<BufferedImage>, Void> worker = new SwingWorker<List<BufferedImage>, Void>() { @Override protected List<BufferedImage> doInBackground() throws Exception { List<BufferedImage> retValue = new LinkedList<>(); try { InputStream pdfInputStream = new FileInputStream(documentFile); PDDocument document = PDDocument.load(pdfInputStream); @SuppressWarnings("unchecked") List<PDPage> pages = document.getDocumentCatalog().getAllPages(); for (PDPage page : pages) { if (dialog.isCanceled()) { document.close(); MainPanel.LOGGER.debug("tab generation aborted"); return null; } BufferedImage image = page.convertToImage(); retValue.add(image); } document.close(); } catch (IOException ex) { throw new DocumentAddException(ex); } return retValue; } @Override protected void done() { } }; worker.addPropertyChangeListener(new SwingWorkerCompletionWaiter(dialog)); worker.execute(); //the dialog will be visible until the SwingWorker is done dialog.setVisible(true); List<BufferedImage> retValue = worker.get(); return retValue; }