List of usage examples for javax.swing SwingWorker execute
public final void execute()
From source file:ca.uviccscu.lp.server.main.MainFrame.java
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed l.info("Hash action activated"); final ActionEvent ev = evt; if (!Shared.hashInProgress) { //final Game gg; if (jTable1.getSelectedRow() >= 0) { DefaultTableModel mdl = (DefaultTableModel) jTable1.getModel(); String name = (String) mdl.getValueAt(jTable1.getSelectedRow(), 0); if (name != null) { MainFrame.lockInterface(); SwingWorker worker = new SwingWorker<Void, Void>() { @Override//from w ww. ja va 2 s .c om public Void doInBackground() { l.trace("Starting hashing"); MainFrame.lockInterface(); Shared.hashInProgress = true; int row = jTable1.getSelectedRow(); String game = (String) jTable1.getModel().getValueAt(row, 0); l.trace("Selection - row: " + row + " and name " + game); int status = GamelistStorage.getGame(game).gameStatus; if (status == 0) { File g = new File(GamelistStorage.getGame(game).gameAbsoluteFolderPath); File tp = new File(SettingsManager.getTorrentFolderPath() + GamelistStorage.getGame(game).gameName + ".torrent"); try { updateTask("Preparing to hash - wait!", true); updateProgressBar(0, 0, 0, "...", false, true); jButton5.setText("STOP"); //jButton5.setForeground(Color.RED); jButton5.setEnabled(true); jButton5.requestFocusInWindow(); MainFrame.setReportingActive(); GamelistStorage.getGame(game).gameStatus = 1; MainFrame.updateGameInterfaceFromStorage(); TOTorrent t = TrackerManager.createNewTorrent(g, tp, new HashingProgressListener(game)); TrackerManager.getCore().addTorrentToTracker(t, tp.getAbsolutePath(), g.getAbsolutePath()); GamelistStorage.getGame(game).gameStatus = 2; MainFrame.updateGameInterfaceFromStorage(); MainFrame.setReportingIdle(); } catch (Exception ex) { l.error("Torrent create failed: " + game, ex); } } else if (status == 1 || status == 2) { l.error("Game torrent already created"); int ans = JOptionPane.showConfirmDialog(null, "This game has already been hashed. Rehash?", "Hashing error", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); if (ans == JOptionPane.OK_OPTION) { GamelistStorage.getGame(game).gameStatus = 0; File tp = new File(Shared.workingDirectory + Shared.torrentStoreSubDirectory + "\\" + GamelistStorage.getGame(game).gameName + ".torrent"); FileUtils.deleteQuietly(tp); Shared.hashInProgress = false; jButton5ActionPerformed(ev); Shared.hashInProgress = true; } else { // } } else { l.error("Game status invalid - hashing aborted"); } return null; } @Override public void done() { MainFrame.setReportingIdle(); jButton5.setText("Hash selected"); //jButton5.setForeground(Color.WHITE); MainFrame.unlockInterface(); Shared.hashInProgress = false; MainFrame.updateGameInterfaceFromStorage(); } }; worker.execute(); } else { l.trace("Empty row - no action required"); } } } else { try { l.trace("Stopping current hashing"); TrackerManager.cancelNewTorrentCreation(); int row = jTable1.getSelectedRow(); String game = (String) jTable1.getModel().getValueAt(row, 0); GamelistStorage.getGame(game).gameStatus = 0; MainFrame.unlockInterface(); MainFrame.updateGameInterfaceFromStorage(); } catch (TOTorrentException ex) { l.info("Abort exception received as expected", ex); } catch (Exception ex) { l.error("Hash abort unexpected exception - abort failed"); } jButton5.setText("Hash selected"); jButton5.setForeground(Color.WHITE); } }
From source file:com.mirth.connect.client.ui.Frame.java
public void sendUsageStatistics() { UpdateSettings updateSettings = null; try {//ww w . ja va 2 s . c o m updateSettings = mirthClient.getUpdateSettings(); } catch (Exception e) { } if (updateSettings != null && updateSettings.getStatsEnabled()) { final String workingId = startWorking("Sending usage statistics..."); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { public Void doInBackground() { try { String usageData = mirthClient.getUsageData(getClientStats()); if (usageData != null) { boolean isSent = ConnectServiceUtil.sendStatistics(PlatformUI.SERVER_ID, PlatformUI.SERVER_VERSION, false, usageData, PlatformUI.HTTPS_PROTOCOLS, PlatformUI.HTTPS_CIPHER_SUITES); if (isSent) { UpdateSettings settings = new UpdateSettings(); settings.setLastStatsTime(System.currentTimeMillis()); mirthClient.setUpdateSettings(settings); } } } catch (ClientException e) { // ignore errors connecting to update/stats server } return null; } public void done() { stopWorking(workingId); } }; worker.execute(); } }
From source file:edu.ku.brc.specify.config.init.SpecifyDBSetupWizard.java
/** * //w ww . ja v a 2 s. com */ public void configureDatabase() { if (wizardType == WizardType.Institution) { setupLoginPrefs(); } if (SpecifyDBSetupWizard.this.listener != null) { SpecifyDBSetupWizard.this.listener.hide(); } SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() { protected boolean isOK = false; /* (non-Javadoc) * @see javax.swing.SwingWorker#doInBackground() */ @Override protected Integer doInBackground() throws Exception { try { String dbName = props.getProperty("dbName"); String hostName = props.getProperty("hostName"); DatabaseDriverInfo driverInfo = (DatabaseDriverInfo) props.get("driverObj"); String connStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Create, hostName, dbName); if (connStr == null) { connStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open, hostName, dbName); } String saUserName = props.getProperty("saUserName"); // Master Username String saPassword = props.getProperty("saPassword"); // Master Password BuildSampleDatabase bsd = new BuildSampleDatabase(); progressFrame = bsd.createProgressFrame(getResourceString("CREATE_DIV")); progressFrame.adjustProgressFrame(); progressFrame.setProcessPercent(true); progressFrame.setOverall(0, 12); UIRegistry.pushWindow(progressFrame); UIHelper.centerAndShow(progressFrame); if (!UIHelper.tryLogin(driverInfo.getDriverClassName(), driverInfo.getDialectClassName(), dbName, connStr, saUserName, saPassword)) { isOK = false; return null; } Session session = HibernateUtil.getCurrentSession(); bsd.setSession(session); AppContextMgr ac = AppContextMgr.getInstance(); Institution institution = ac.getClassObject(Institution.class); SpecifyUser user = ac.getClassObject(SpecifyUser.class); DisciplineType disciplineType = (DisciplineType) props.get("disciplineType"); DataType dataType = AppContextMgr.getInstance().getClassObject(DataType.class); session.lock(institution, LockMode.NONE); session.lock(dataType, LockMode.NONE); bsd.setDataType(dataType); Division division = bsd.createEmptyDivision(institution, disciplineType, user, props, true, true, true); if (division != null) { isOK = division != null; progressFrame.incOverall(); if (isOK) { SpecifySchemaUpdateService .addIPadExporterTables(DBConnection.getInstance().getConnection()); FixDBAfterLogin.fixUserPermissions(true); saveFormatters(); } progressFrame.setVisible(false); progressFrame.dispose(); } else { isOK = false; } } catch (Exception ex) { //edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SpecifyDBSetupWizard.class, ex); ex.printStackTrace(); } return null; } /* (non-Javadoc) * @see javax.swing.SwingWorker#done() */ @Override protected void done() { // Create Version Record and copy if there is a connection if (DBConnection.getInstance().getConnection() != null) { String resAppVersion = UIRegistry.getAppVersion(); String dbVersion = SchemaUpdateService.getInstance().getDBSchemaVersionFromXML(); SpVersion.createInitialRecord(DBConnection.getInstance().getConnection(), resAppVersion, dbVersion); if (UIRegistry.isMobile()) { DBConnection.setCopiedToMachineDisk(true); } } JOptionPane.showMessageDialog(UIRegistry.getTopWindow(), getLocalizedMessage("BLD_DONE", getResourceString(isOK ? "BLD_OK" : "BLD_NOTOK")), getResourceString("COMPLETE"), JOptionPane.INFORMATION_MESSAGE); if (listener != null) { listener.hide(); listener.finished(); } } }; worker.execute(); }
From source file:com.mirth.connect.client.ui.Frame.java
public void doStartConnector() { final List<DashboardStatus> selectedStatuses = dashboardPanel.getSelectedStatuses(); if (selectedStatuses.size() == 0) { return;/*from w ww. ja va2 s .c om*/ } final String workingId = startWorking("Starting connectors..."); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { public Void doInBackground() { Map<String, List<Integer>> connectorInfo = new HashMap<String, List<Integer>>(); for (DashboardStatus dashboardStatus : selectedStatuses) { String channelId = dashboardStatus.getChannelId(); Integer metaDataId = dashboardStatus.getMetaDataId(); if (metaDataId != null) { if (!connectorInfo.containsKey(channelId)) { connectorInfo.put(channelId, new ArrayList<Integer>()); } connectorInfo.get(channelId).add(metaDataId); } } try { if (!connectorInfo.isEmpty()) { mirthClient.startConnectors(connectorInfo); } } catch (ClientException e) { alertThrowable(PlatformUI.MIRTH_FRAME, e); } return null; } public void done() { doRefreshStatuses(true); stopWorking(workingId); } }; worker.execute(); }
From source file:com.mirth.connect.client.ui.Frame.java
public void doStopConnector() { final List<DashboardStatus> selectedStatuses = dashboardPanel.getSelectedStatuses(); if (selectedStatuses.size() == 0) { return;// w w w . j a v a2 s.c om } boolean warnQueueDisabled = false; for (Iterator<DashboardStatus> it = selectedStatuses.iterator(); it.hasNext();) { DashboardStatus dashboardStatus = it.next(); if (dashboardStatus.getMetaDataId() != 0 && !dashboardStatus.isQueueEnabled()) { warnQueueDisabled = true; it.remove(); } } final String workingId = startWorking("Stopping connectors..."); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { public Void doInBackground() { Map<String, List<Integer>> connectorInfo = new HashMap<String, List<Integer>>(); for (DashboardStatus dashboardStatus : selectedStatuses) { String channelId = dashboardStatus.getChannelId(); Integer metaDataId = dashboardStatus.getMetaDataId(); if (metaDataId != null) { if (!connectorInfo.containsKey(channelId)) { connectorInfo.put(channelId, new ArrayList<Integer>()); } connectorInfo.get(channelId).add(metaDataId); } } try { if (!connectorInfo.isEmpty()) { mirthClient.stopConnectors(connectorInfo); } } catch (ClientException e) { alertThrowable(PlatformUI.MIRTH_FRAME, e); } return null; } public void done() { doRefreshStatuses(true); stopWorking(workingId); } }; worker.execute(); if (warnQueueDisabled) { alertWarning(this, "<html>One or more destination connectors were not stopped because queueing was not enabled.<br>Queueing must be enabled for a destination connector to be stopped individually.</html>"); } }
From source file:com.mirth.connect.client.ui.Frame.java
public void doStart() { final Set<DashboardStatus> selectedStatuses = dashboardPanel.getSelectedChannelStatuses(); if (selectedStatuses.size() == 0) { return;//from w w w.ja v a 2 s . c o m } if (!getStatusesWithDependencies(selectedStatuses, ChannelTask.START_RESUME)) { return; } final String workingId = startWorking("Starting or resuming channels..."); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { public Void doInBackground() { Set<String> startChannelIds = new HashSet<String>(); Set<String> resumeChannelIds = new HashSet<String>(); for (DashboardStatus dashboardStatus : selectedStatuses) { if (dashboardStatus.getState() == DeployedState.PAUSED) { resumeChannelIds.add(dashboardStatus.getChannelId()); } else { startChannelIds.add(dashboardStatus.getChannelId()); } } try { if (!startChannelIds.isEmpty()) { mirthClient.startChannels(startChannelIds); } if (!resumeChannelIds.isEmpty()) { mirthClient.resumeChannels(resumeChannelIds); } } catch (ClientException e) { alertThrowable(PlatformUI.MIRTH_FRAME, e); } return null; } public void done() { doRefreshStatuses(true); stopWorking(workingId); } }; worker.execute(); }
From source file:edu.ku.brc.specify.tasks.subpane.images.ImagesPane.java
/** * /*from w ww .j ava 2s .co m*/ */ private void searchForRecordSetAttachments() { final String MEGS = "MEGS"; final String STATUSBAR_NAME = "ImageSearchStatusBar"; rowsVector.clear(); items = recordSet.getOrderedItems(); final int numItems = items.size(); SwingWorker<Integer, Integer> backupWorker = new SwingWorker<Integer, Integer>() { @Override protected Integer doInBackground() throws Exception { final DBTableInfo ti = DBTableIdMgr.getInstance().getInfoById(recordSet.getDbTableId()); boolean isAttachmentTableItself = ti.getTableId() == Attachment.getClassTableId(); String sql; if (!isAttachmentTableItself) { sql = "SELECT a.AttachmentID, a.TableID, a.Title, a.AttachmentLocation, a.MimeType FROM attachment a " + "INNER JOIN %sattachment coa ON a.AttachmentID = coa.AttachmentID " + "WHERE coa.%s IN (%s) %s ORDER BY FIELD(%s, %s)"; } else { sql = "SELECT a.AttachmentID, a.TableID, a.Title, a.AttachmentLocation, a.MimeType FROM attachment a " + "WHERE AttachmentID IN (%s) ORDER BY FIELD(a.AttachmentID, %s)"; } int batchSize = 500; int attchIndex = 0; int batches = (numItems / batchSize) + (numItems % batchSize == 0 ? 0 : 1); if (numItems < batchSize) { batchSize = numItems; } Statement stmt = null; try { stmt = DBConnection.getInstance().getConnection().createStatement(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < batches; i++) { firePropertyChange(MEGS, 0, i + 1); sb.setLength(0); for (int j = 0; j < batchSize && attchIndex < numItems; j++) { RecordSetItemIFace rsi = items.get(attchIndex++); if (j > 0) sb.append(','); sb.append(rsi.getRecordId().toString()); } String filter = getFilterString(); if (StringUtils.isNotEmpty(filter)) { filter = " AND " + filter; } String fullSQL; if (!isAttachmentTableItself) { fullSQL = String.format(sql, ti.getName(), ti.getIdColumnName(), sb.toString(), filter, ti.getIdColumnName(), sb.toString()); } else { fullSQL = String.format(sql, sb.toString(), filter, sb.toString()); } log.debug(fullSQL); ResultSet rs = stmt.executeQuery(fullSQL); while (rs.next()) { ImageDataItem imgDataItem = new ImageDataItem(rs.getInt(1), rs.getInt(2), rs.getString(3), rs.getString(4), rs.getString(5)); rowsVector.add(imgDataItem); } rs.close(); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (stmt != null) stmt.close(); } catch (Exception e) { } } return null; } @Override protected void done() { super.done(); getStatusBar().setProgressDone(STATUSBAR_NAME); clearSimpleGlassPaneMsg(); if (rowsVector != null && rowsVector.size() > 0) { gridPanel.setItemList(rowsVector); JScrollPane sb = new JScrollPane(gridPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); add(sb, BorderLayout.CENTER); ((AttachmentsTask) task).attachmentSearchDone(ImagesPane.this); } else { ((AttachmentsTask) task).attachmentSearchDone(null); writeTimedSimpleGlassPaneMsg(getNotFoundMessage()); } } }; final JStatusBar statusBar = getStatusBar(); statusBar.setIndeterminate(STATUSBAR_NAME, true); writeSimpleGlassPaneMsg(getResourceString("ATTCH_SEARCH_IMGS"), 24); backupWorker.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent evt) { if (MEGS.equals(evt.getPropertyName())) { Integer value = (Integer) evt.getNewValue(); int val = (int) (((double) value / (double) numItems) * 100.0); statusBar.setText(Integer.toString(val));//getLocalizedMessage("MySQLBackupService.BACKUP_MEGS", val)); } } }); backupWorker.execute(); }
From source file:edu.ku.brc.specify.datamodel.busrules.CollectionBusRules.java
/** * /*from ww w.j av a 2 s.c o m*/ */ private void addNewCollection() { if (!DivisionBusRules.checkForParentSave(formViewObj, Discipline.getClassTableId())) { return; } UIRegistry.loadAndPushResourceBundle("specifydbsetupwiz"); UIRegistry.writeSimpleGlassPaneMsg("Building Collection...", 20); // I18N isOKToCont = true; final AppContextMgr acm = AppContextMgr.getInstance(); final SpecifyDBSetupWizard wizardPanel = new SpecifyDBSetupWizard( SpecifyDBSetupWizard.WizardType.Collection, null); String msg = UIRegistry.getResourceString("CREATECOLL"); final CustomDialog dlg = new CustomDialog((Frame) UIRegistry.getMostRecentWindow(), "", true, CustomDialog.NONE_BTN, wizardPanel); dlg.setCustomTitleBar(msg); wizardPanel.setListener(new SpecifyDBSetupWizard.WizardListener() { @Override public void cancelled() { isOKToCont = false; dlg.setVisible(false); } @Override public void finished() { dlg.setVisible(false); } @Override public void hide() { dlg.setVisible(false); } @Override public void panelChanged(String title) { dlg.setTitle(title); } @Override public void helpContextChanged(String helpTarget) { } }); dlg.createUI(); dlg.pack(); UIHelper.centerAndShow(dlg); UIRegistry.popResourceBundle(); if (!isOKToCont) { UIRegistry.clearSimpleGlassPaneMsg(); return; } wizardPanel.processDataForNonBuild(); final BuildSampleDatabase bldSampleDB = new BuildSampleDatabase(); final ProgressFrame progressFrame = bldSampleDB.createProgressFrame(msg); // I18N progressFrame.turnOffOverAll(); progressFrame.setProcess(0, 4); progressFrame.setProcessPercent(true); progressFrame.getCloseBtn().setVisible(false); progressFrame.setAlwaysOnTop(true); progressFrame.adjustProgressFrame(); UIHelper.centerAndShow(progressFrame); SwingWorker<Integer, Integer> bldWorker = new SwingWorker<Integer, Integer>() { Collection newCollection = null; /* (non-Javadoc) * @see javax.swing.SwingWorker#doInBackground() */ @Override protected Integer doInBackground() throws Exception { Session session = null; try { session = HibernateUtil.getNewSession(); DataProviderSessionIFace hSession = new HibernateDataProviderSession(session); Discipline discipline = (Discipline) formViewObj.getMVParent().getMultiViewParent().getData(); //Institution institution = acm.getClassObject(Institution.class); SpecifyUser specifyAdminUser = acm.getClassObject(SpecifyUser.class); Agent userAgent = (Agent) hSession .getData("FROM Agent WHERE id = " + Agent.getUserAgent().getId()); Properties props = wizardPanel.getProps(); DisciplineType disciplineType = DisciplineType.getByName(discipline.getType()); discipline = (Discipline) session.merge(discipline); specifyAdminUser = (SpecifyUser) hSession .getData("FROM SpecifyUser WHERE id = " + specifyAdminUser.getId()); bldSampleDB.setSession(session); AutoNumberingScheme catNumScheme = bldSampleDB.createAutoNumScheme(props, "catnumfmt", "Catalog Numbering Scheme", CollectionObject.getClassTableId()); /*AutoNumberingScheme accNumScheme = null; if (institution.getIsAccessionsGlobal()) { List<?> list = hSession.getDataList("FROM AutoNumberingScheme WHERE tableNumber = "+Accession.getClassTableId()); if (list != null && list.size() == 1) { accNumScheme = (AutoNumberingScheme)list.get(0); } } else { accNumScheme = bldSampleDB.createAutoNumScheme(props, "accnumfmt", "Accession Numbering Scheme", Accession.getClassTableId()); // I18N }*/ newCollection = bldSampleDB.createEmptyCollection(discipline, props.getProperty("collPrefix").toString(), props.getProperty("collName").toString(), userAgent, specifyAdminUser, catNumScheme, disciplineType.isEmbeddedCollecingEvent()); acm.setClassObject(SpecifyUser.class, specifyAdminUser); Agent.setUserAgent(userAgent); } catch (Exception ex) { ex.printStackTrace(); } finally { if (session != null) { session.close(); } } bldSampleDB.setDataType(null); return null; } @Override protected void done() { super.done(); progressFrame.setVisible(false); progressFrame.dispose(); if (newCollection != null) { List<?> dataItems = null; FormViewObj dispFVO = formViewObj.getMVParent().getMultiViewParent() .getCurrentViewAsFormViewObj(); Discipline discipline = (Discipline) dispFVO.getDataObj(); DataProviderSessionIFace pSession = null; try { pSession = DataProviderFactory.getInstance().createSession(); discipline = (Discipline) pSession .getData("FROM Discipline WHERE id = " + discipline.getId()); //formViewObj.getMVParent().getMultiViewParent().setData(division); acm.setClassObject(Discipline.class, discipline); dataItems = pSession.getDataList("FROM Discipline"); if (dataItems.get(0) instanceof Object[]) { Vector<Object> dataList = new Vector<Object>(); for (Object row : dataItems) { Object[] cols = (Object[]) row; dataList.add(cols[0]); } dataItems = dataList; } } catch (Exception ex) { System.err.println(ex); ex.printStackTrace(); } finally { if (pSession != null) { pSession.close(); } } int curInx = dispFVO.getRsController().getCurrentIndex(); dispFVO.setDataObj(dataItems); dispFVO.getRsController().setIndex(curInx); //UIRegistry.clearSimpleGlassPaneMsg(); UIRegistry.showLocalizedMsg("Specify.ABT_EXIT"); CommandDispatcher.dispatch(new CommandAction(BaseTask.APP_CMD_TYPE, BaseTask.APP_REQ_EXIT)); } else { // error creating } UIRegistry.clearSimpleGlassPaneMsg(); } }; bldWorker.execute(); }
From source file:edu.ku.brc.specify.tasks.subpane.lm.LifeMapperPane.java
/** * @param searchStr//from w w w.jav a 2 s .c om * @param cbListener */ private void doSearchGenusSpecies(final String searchStr, final LMSearchCallbackListener cbListener) { UsageTracker.incrUsageCount("LM.GenSpSearch"); updateMyDataUIState(false); final SimpleGlassPane glassPane = writeSimpleGlassPaneMsg(getLocalizedMessage("LifeMapperTask.PROCESSING"), GLASS_FONT_SIZE); glassPane.setTextYPos((int) ((double) getSize().height * 0.25)); SwingWorker<String, String> worker = new SwingWorker<String, String>() { @Override protected String doInBackground() throws Exception { HttpClient httpClient = new HttpClient(); httpClient.getParams().setParameter("http.useragent", getClass().getName()); //$NON-NLS-1$ httpClient.getParams().setParameter("http.socket.timeout", 15000); String genusSpecies = StringUtils.replace(searchStr, " ", "%20"); String url = "http://www.lifemapper.org/hint/species/" + genusSpecies + "?maxReturned=1000&format=json"; //System.out.println(url); GetMethod getMethod = new GetMethod(url); try { httpClient.executeMethod(getMethod); return getMethod.getResponseBodyAsString(); } catch (java.net.UnknownHostException uex) { //log.error(uex.getMessage()); } catch (Exception e) { e.printStackTrace(); UsageTracker.incrUsageCount("LM.GenSpSearchErr"); } return null; } @SuppressWarnings("unchecked") @Override protected void done() { super.done(); ArrayList<OccurrenceSetIFace> items = null; String errMsgKey = "LifeMapperTask.PROC_ERR"; String responseString; try { responseString = get(); //System.out.println(responseString); if (responseString != null) { if (responseString.startsWith("None of the species")) { errMsgKey = "LM_NO_LM_DATA"; } else if (responseString.startsWith("Search too broad")) { errMsgKey = "LM_TOO_BROAD"; } else if (StringUtils.isNotEmpty(responseString) && StringUtils.contains(responseString.toLowerCase(), "{")) { JSONTokener tok = new JSONTokener(responseString); while (tok.more()) { JSONObject obj = (JSONObject) tok.nextValue(); JSONArray pointArray = (JSONArray) obj.get("columns"); Iterator<Object> iter = (Iterator<Object>) pointArray.iterator(); while (iter.hasNext()) { JSONArray arrayObj = (JSONArray) iter.next(); //System.out.println(arrayObj); Iterator<Object> iterInner = (Iterator<Object>) arrayObj.iterator(); while (iterInner.hasNext()) { JSONObject pObj = (JSONObject) iterInner.next(); String binomial = (String) pObj.get("binomial"); String gnSpName = (String) pObj.get("name"); String numPoints = (String) pObj.get("numPoints"); String occurrenceSet = (String) pObj.get("occurrenceSet"); if (StringUtils.isNotEmpty(gnSpName) && StringUtils.isNotEmpty(numPoints) && StringUtils.isNotEmpty(occurrenceSet)) { try { int numPnts = Integer.parseInt(numPoints); int occurId = Integer.parseInt(occurrenceSet); if (numPnts > 0 && occurId > 0) { if (items == null) { items = new ArrayList<OccurrenceSetIFace>(); } items.add(new GenusSpeciesDataItem( String.format("%s (%s)", gnSpName, numPoints), occurrenceSet, binomial)); } } catch (Exception ex) { // no op } errMsgKey = items == null || items.size() == 0 ? "LM_NO_LOCAL_DATA" : null; } } } } } } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } if (errMsgKey != null) { showErrorMsg(glassPane, errMsgKey); cbListener.noItems(); } else { //System.out.println("Num Genus/Species: "+items.size()); clearSimpleGlassPaneMsg(); cbListener.itemsFound(items); } } }; worker.execute(); }
From source file:edu.ku.brc.specify.dbsupport.cleanuptools.AgentCleanupProcessor.java
/** * @param fii/*from ww w. ja va 2 s . co m*/ */ private void checkForAddrs(final FindItemInfo fii) { System.out.println("\ncheckForAddrs (async)"); SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() { boolean hasAddrs = false; @Override protected Object doInBackground() throws Exception { String inClause = fii.getInClause(true); String sql = String.format("SELECT COUNT(*) FROM address WHERE AgentID IN %s", inClause); hasAddrs = BasicSQLUtils.getCountAsInt(sql) > 0; return null; } @Override protected void done() { if (hasAddrs) { /*AddressCleanupDlg addrCleanup = new AddressCleanupDlg(fii); // NOTE: SQL is done on UI thread addrCleanup.fillModel(); if (!addrCleanup.isSingle()) { addrCleanup.pack(); addrCleanup.setSize(800, 500); UIHelper.centerWindow(addrCleanup); addrCleanup.setVisible(true); isContinuing = !addrCleanup.isCancelled(); } List<AddrInfo> addrIdList = addrCleanup.getAddrIds(); if (doUpdates) { if (addrIdList != null && addrIdList.size() > 0) { if (!cleanupAddresses(fii, addrIdList)) { showError(String.format("There was an error cleaning up addresses for agent'%s'", fii.getValue().toString())); isContinuing = false; } } }*/ MultipleRecordCleanupDlg mrcDlg = null; try { isSkipping = false; MultipleRecordComparer mrc = new MultipleRecordComparer(fii, Agent.getClassTableId(), Address.getClassTableId(), AgentVariant.getClassTableId() //AccessionAgent.getClassTableId() //AgentSpecialty.getClassTableId(), //AgentGeography.getClassTableId() ); mrc.setSingleRowIncluded(false, false, false, false); mrc.addDisplayColumn("Agent's Name"); mrc.loadData(); if (mrc.hasColmnsOfDataThatsDiff() || mrc.hasKidsDataThatsDiff()) { mrcDlg = new MultipleRecordCleanupDlg(mrc, "Agent Cleanup"); mrcDlg.createUI(); if (!mrcDlg.isSingle()) { mrcDlg.pack(); mrcDlg.setSize(800, 500); UIHelper.centerWindow(mrcDlg); mrcDlg.toFront(); prgDlg.toBack(); mrcDlg.setVisible(true); prgDlg.toFront(); isContinuing = !mrcDlg.isCancelled(); isSkipping = mrcDlg.getBtnPressed() == CustomDialog.APPLY_BTN; } if (isContinuing) { MergeInfo mainItem = mrcDlg.getMainMergedInfo(); List<MergeInfo> kidItems = mrcDlg.getKidsMergedInfo(); if (!cleanupMerges(Agent.getClassTableId(), mainItem, kidItems)) { String msg = String.format( "There was an error cleaning up addresses for agent '%s'", fii.getValue().toString()); showProcessingMessage(msg); log.error(msg); isContinuing = false; } if (!deleteMerges(Agent.getClassTableId(), mainItem, kidItems)) { String msg = String.format( "There was an error cleaning up addresses for agent '%s'", fii.getValue().toString()); showProcessingMessage(msg); log.error(msg); isContinuing = false; } } } else if (mrc.hasRecords()) { log.debug("Here"); } else { isContinuing = true; } } catch (Exception ex) { ex.printStackTrace(); } if (isContinuing) { prgDlg.toFront(); doMergeOfAgents(fii); } else { prgDlg.setVisible(false); prgDlg.dispose(); } } else { doMergeOfAgents(fii); } } }; worker.execute(); }