List of usage examples for javax.swing JOptionPane QUESTION_MESSAGE
int QUESTION_MESSAGE
To view the source code for javax.swing JOptionPane QUESTION_MESSAGE.
Click Source Link
From source file:com.diversityarrays.kdxplore.KDXploreFrame.java
private void doBackupDatabase() { switch (backupProviders.size()) { case 0:/*from www.j ava2 s . co m*/ MsgBox.warn(this, Msg.MSG_NO_DB_BACKUP_APPS_AVAILABLE(), getTitle()); return; case 1: backupProviders.get(0).doDatabaseBackup(this); break; default: Map<String, BackupProvider> bpByName = backupProviders.stream() .collect(Collectors.toMap(BackupProvider::getBackupProviderName, Function.identity())); String[] choices = backupProviders.stream().map(BackupProvider::getBackupProviderName) .collect(Collectors.toList()).toArray(new String[backupProviders.size()]); Object choice = JOptionPane.showInputDialog(this, Msg.MSG_SELECT_APP_FOR_BACKUP(), Msg.TITLE_BACKUP_DATABASE(), JOptionPane.QUESTION_MESSAGE, null, choices, choices[0]); if (choice != null) { BackupProvider bp = bpByName.get(choice); bp.doDatabaseBackup(this); } break; } }
From source file:com.freedomotic.jfrontend.MainWindow.java
/** * // ww w. j a v a 2 s . co m * @param evt */ private void mnuAddDuplicateEnvironmentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuAddDuplicateEnvironmentActionPerformed EnvironmentLogic newEnv = api.environments().copy(drawer.getCurrEnv()); String input = JOptionPane.showInputDialog(this, i18n.msg("enter_new_name_for_env") + newEnv.getPojo().getName(), i18n.msg("environment_duplicate_popup_title"), JOptionPane.QUESTION_MESSAGE); if (input != null && !input.isEmpty()) { newEnv.getPojo().setName(input.trim()); newEnv.setSource(new File( drawer.getCurrEnv().getSource().getParentFile() + "/" + newEnv.getPojo().getUUID() + ".xenv")); setEnvironment(api.environments().findOne(newEnv.getPojo().getUUID())); } else { JOptionPane.showMessageDialog(this, i18n.msg("environment_name_cannot_be_empty"), i18n.msg("environment_rename_popup_title"), JOptionPane.ERROR_MESSAGE); } checkDeletableEnvironments(); }
From source file:nosqltools.MainForm.java
private void file_closeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_file_closeActionPerformed if (JOptionPane.showConfirmDialog(null, "Are you sure you want to exit?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION) dispose();//from ww w.j a v a 2 s .c o m }
From source file:com.freedomotic.jfrontend.MainWindow.java
/** * // www . ja v a2s.co m * @param evt */ private void mnuRenameEnvironmentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuRenameEnvironmentActionPerformed String input = JOptionPane.showInputDialog(this, i18n.msg("enter_new_name_for_env", new Object[] { drawer.getCurrEnv().getPojo().getName() }), i18n.msg("environment_rename_popup_title"), JOptionPane.QUESTION_MESSAGE); if (input != null) { if (!input.isEmpty()) { drawer.getCurrEnv().getPojo().setName(input.trim()); setMapTitle(drawer.getCurrEnv().getPojo().getName()); } else { JOptionPane.showMessageDialog(this, i18n.msg("environment_name_cannot_be_empty"), i18n.msg("environment_rename_popup_title"), JOptionPane.ERROR_MESSAGE); } } }
From source file:com.mirth.connect.client.ui.ChannelPanel.java
public void importGroup(ChannelGroup importGroup, boolean showAlerts, boolean synchronous) { // First consolidate and import code template libraries Map<String, CodeTemplateLibrary> codeTemplateLibraryMap = new LinkedHashMap<String, CodeTemplateLibrary>(); Set<String> codeTemplateIds = new HashSet<String>(); for (Channel channel : importGroup.getChannels()) { if (channel.getCodeTemplateLibraries() != null) { for (CodeTemplateLibrary library : channel.getCodeTemplateLibraries()) { CodeTemplateLibrary matchingLibrary = codeTemplateLibraryMap.get(library.getId()); if (matchingLibrary != null) { for (CodeTemplate codeTemplate : library.getCodeTemplates()) { if (codeTemplateIds.add(codeTemplate.getId())) { matchingLibrary.getCodeTemplates().add(codeTemplate); }//from w w w . j a va2 s . c o m } } else { matchingLibrary = library; codeTemplateLibraryMap.put(matchingLibrary.getId(), matchingLibrary); List<CodeTemplate> codeTemplates = new ArrayList<CodeTemplate>(); for (CodeTemplate codeTemplate : matchingLibrary.getCodeTemplates()) { if (codeTemplateIds.add(codeTemplate.getId())) { codeTemplates.add(codeTemplate); } } matchingLibrary.setCodeTemplates(codeTemplates); } // Combine the library enabled / disabled channel IDs matchingLibrary.getEnabledChannelIds().addAll(library.getEnabledChannelIds()); matchingLibrary.getEnabledChannelIds().add(channel.getId()); matchingLibrary.getDisabledChannelIds().addAll(library.getDisabledChannelIds()); matchingLibrary.getDisabledChannelIds().removeAll(matchingLibrary.getEnabledChannelIds()); } channel.getCodeTemplateLibraries().clear(); } } List<CodeTemplateLibrary> codeTemplateLibraries = new ArrayList<CodeTemplateLibrary>( codeTemplateLibraryMap.values()); parent.removeInvalidItems(codeTemplateLibraries, CodeTemplateLibrary.class); if (CollectionUtils.isNotEmpty(codeTemplateLibraries)) { boolean importLibraries; String importChannelCodeTemplateLibraries = Preferences.userNodeForPackage(Mirth.class) .get("importChannelCodeTemplateLibraries", null); if (importChannelCodeTemplateLibraries == null) { JCheckBox alwaysChooseCheckBox = new JCheckBox( "Always choose this option by default in the future (may be changed in the Administrator settings)"); Object[] params = new Object[] { "Group \"" + importGroup.getName() + "\" has code template libraries included with it. Would you like to import them?", alwaysChooseCheckBox }; int result = JOptionPane.showConfirmDialog(this, params, "Select an Option", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (result == JOptionPane.YES_OPTION || result == JOptionPane.NO_OPTION) { importLibraries = result == JOptionPane.YES_OPTION; if (alwaysChooseCheckBox.isSelected()) { Preferences.userNodeForPackage(Mirth.class).putBoolean("importChannelCodeTemplateLibraries", importLibraries); } } else { return; } } else { importLibraries = Boolean.parseBoolean(importChannelCodeTemplateLibraries); } if (importLibraries) { CodeTemplateImportDialog dialog = new CodeTemplateImportDialog(parent, codeTemplateLibraries, false, true); if (dialog.wasSaved()) { CodeTemplateLibrarySaveResult updateSummary = parent.codeTemplatePanel.attemptUpdate( dialog.getUpdatedLibraries(), new HashMap<String, CodeTemplateLibrary>(), dialog.getUpdatedCodeTemplates(), new HashMap<String, CodeTemplate>(), true, null, null); if (updateSummary == null || updateSummary.isOverrideNeeded() || !updateSummary.isLibrariesSuccess()) { return; } else { for (CodeTemplateUpdateResult result : updateSummary.getCodeTemplateResults().values()) { if (!result.isSuccess()) { return; } } } parent.codeTemplatePanel.doRefreshCodeTemplates(); } } } List<Channel> successfulChannels = new ArrayList<Channel>(); for (Channel channel : importGroup.getChannels()) { Channel importChannel = importChannel(channel, false, false); if (importChannel != null) { successfulChannels.add(importChannel); } } if (!StringUtils.equals(importGroup.getId(), ChannelGroup.DEFAULT_ID)) { ChannelTreeTableModel model = (ChannelTreeTableModel) channelTable.getTreeTableModel(); AbstractChannelTableNode importGroupNode = null; String groupName = importGroup.getName(); String tempId; try { tempId = parent.mirthClient.getGuid(); } catch (ClientException e) { tempId = UUID.randomUUID().toString(); } // Check to see that the channel name doesn't already exist. if (!checkGroupName(groupName)) { if (!parent.alertOption(parent, "Would you like to overwrite the existing group? Choose 'No' to create a new group.")) { importGroup.setRevision(0); do { groupName = JOptionPane.showInputDialog(this, "Please enter a new name for the group.", groupName); if (groupName == null) { return; } } while (!checkGroupName(groupName)); importGroup.setId(tempId); importGroup.setName(groupName); } else { MutableTreeTableNode root = (MutableTreeTableNode) model.getRoot(); for (Enumeration<? extends MutableTreeTableNode> groupNodes = root.children(); groupNodes .hasMoreElements();) { AbstractChannelTableNode groupNode = (AbstractChannelTableNode) groupNodes.nextElement(); if (StringUtils.equals(groupNode.getGroupStatus().getGroup().getName(), groupName)) { importGroupNode = groupNode; } } } } else { // Start the revision number over for a new channel group importGroup.setRevision(0); // If the channel name didn't already exist, make sure // the id doesn't exist either. if (!checkGroupId(importGroup.getId())) { importGroup.setId(tempId); } } Set<ChannelGroup> channelGroups = new HashSet<ChannelGroup>(); Set<String> removedChannelGroupIds = new HashSet<String>(groupStatuses.keySet()); removedChannelGroupIds.remove(ChannelGroup.DEFAULT_ID); MutableTreeTableNode root = (MutableTreeTableNode) channelTable.getTreeTableModel().getRoot(); if (root == null) { return; } for (Enumeration<? extends MutableTreeTableNode> groupNodes = root.children(); groupNodes .hasMoreElements();) { ChannelGroup group = ((AbstractChannelTableNode) groupNodes.nextElement()).getGroupStatus() .getGroup(); if (!StringUtils.equals(group.getId(), ChannelGroup.DEFAULT_ID)) { // If the current group is the one we're overwriting, merge the channels if (importGroupNode != null && StringUtils.equals(group.getId(), importGroupNode.getGroupStatus().getGroup().getId())) { group = importGroup; group.setRevision(importGroupNode.getGroupStatus().getGroup().getRevision()); Set<String> channelIds = new HashSet<String>(); for (Channel channel : group.getChannels()) { channelIds.add(channel.getId()); } // Add the imported channels for (Channel channel : successfulChannels) { channelIds.add(channel.getId()); } List<Channel> channels = new ArrayList<Channel>(); for (String channelId : channelIds) { channels.add(new Channel(channelId)); } group.setChannels(channels); } channelGroups.add(group); removedChannelGroupIds.remove(group.getId()); } } if (importGroupNode == null) { List<Channel> channels = new ArrayList<Channel>(); for (Channel channel : successfulChannels) { channels.add(new Channel(channel.getId())); } importGroup.setChannels(channels); channelGroups.add(importGroup); removedChannelGroupIds.remove(importGroup.getId()); } Set<String> channelIds = new HashSet<String>(); for (Channel channel : importGroup.getChannels()) { channelIds.add(channel.getId()); } for (ChannelGroup group : channelGroups) { if (group != importGroup) { for (Iterator<Channel> channels = group.getChannels().iterator(); channels.hasNext();) { if (!channelIds.add(channels.next().getId())) { channels.remove(); } } } } attemptUpdate(channelGroups, removedChannelGroupIds, false); } if (synchronous) { retrieveChannels(); updateModel(getCurrentTableState()); updateTasks(); parent.setSaveEnabled(false); } else { doRefreshChannels(); } }
From source file:fll.scheduler.SchedulerUI.java
/** * Prompt the user for which columns represent subjective categories. * /*from ww w . j a v a 2s . c o m*/ * @param parentComponent the parent for the dialog * @param columnInfo the column information * @return the list of subjective information the user choose */ public static List<SubjectiveStation> gatherSubjectiveStationInformation(final Component parentComponent, final ColumnInformation columnInfo) { final List<String> unusedColumns = columnInfo.getUnusedColumns(); final List<JCheckBox> checkboxes = new LinkedList<JCheckBox>(); final List<JFormattedTextField> subjectiveDurations = new LinkedList<JFormattedTextField>(); final Box optionPanel = Box.createVerticalBox(); optionPanel.add(new JLabel("Specify which columns in the data file are for subjective judging")); final JPanel grid = new JPanel(new GridLayout(0, 2)); optionPanel.add(grid); grid.add(new JLabel("Data file column")); grid.add(new JLabel("Duration (minutes)")); for (final String column : unusedColumns) { if (null != column && column.length() > 0) { final JCheckBox checkbox = new JCheckBox(column); checkboxes.add(checkbox); final JFormattedTextField duration = new JFormattedTextField( Integer.valueOf(SchedParams.DEFAULT_SUBJECTIVE_MINUTES)); duration.setColumns(4); subjectiveDurations.add(duration); grid.add(checkbox); grid.add(duration); } } final List<SubjectiveStation> subjectiveHeaders; if (!checkboxes.isEmpty()) { JOptionPane.showMessageDialog(parentComponent, optionPanel, "Choose Subjective Columns", JOptionPane.QUESTION_MESSAGE); subjectiveHeaders = new LinkedList<SubjectiveStation>(); for (int i = 0; i < checkboxes.size(); ++i) { final JCheckBox box = checkboxes.get(i); final JFormattedTextField duration = subjectiveDurations.get(i); if (box.isSelected()) { subjectiveHeaders .add(new SubjectiveStation(box.getText(), ((Number) duration.getValue()).intValue())); } } } else { subjectiveHeaders = Collections.emptyList(); } if (LOGGER.isTraceEnabled()) { LOGGER.trace("Subjective headers selected: " + subjectiveHeaders); } return subjectiveHeaders; }
From source file:com.pianobakery.complsa.MainGui.java
public void removeSearchCorpMethod() { File theFile = searchCorpusModel.get(searchCorpComboBox.getSelectedItem()); int result = JOptionPane.showConfirmDialog(null, "Do you want to continue?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (result == JOptionPane.NO_OPTION || result == JOptionPane.CANCEL_OPTION) { return;//from w w w . j av a 2s .c o m } if (theFile != null) { addRemoveItemToTopicSearchBoxTaskWithBar(getProgressBarWithTitleLater("Please wait...", false), theFile, false, false); //addRemoveItemToTopicBox(theFile, false, false); } else if (theFile == null) { try { searchCorpComboBox.removeItemAt(0); System.out.printf("Items of select Search Corps: " + searchCorpComboBox.getItemAt(0)); } catch (ArrayIndexOutOfBoundsException e2) { JOptionPane.showMessageDialog(null, "Keine Search Corps mehr vorhanden"); } } }
From source file:edu.ku.brc.specify.config.ResourceImportExportDlg.java
/** * /*from ww w . j av a 2 s .c om*/ */ protected void importResource() { int levelIndex = levelCBX.getSelectedIndex(); if (levelIndex > -1) { String importedName = null; final String IMP_DIR_PREF = "RES_LAST_IMPORT_DIR"; String initalImportDir = AppPreferences.getLocalPrefs().get(IMP_DIR_PREF, getUserHomeDir()); FileDialog fileDlg = new FileDialog(this, getResourceString("RIE_IMPORT_RES"), FileDialog.LOAD); File impDir = new File(initalImportDir); if (StringUtils.isNotEmpty(initalImportDir) && impDir.exists()) { fileDlg.setDirectory(initalImportDir); } UIHelper.centerAndShow(fileDlg); String dirStr = fileDlg.getDirectory(); String fileName = fileDlg.getFile(); if (StringUtils.isNotEmpty(dirStr) && StringUtils.isNotEmpty(fileName)) { AppPreferences.getLocalPrefs().put(IMP_DIR_PREF, dirStr); String data = null; String fullFileName = dirStr + File.separator + fileName; File importFile = new File(fullFileName); if (importFile.exists()) { String repResourceName = getSpReportResourceName(importFile); boolean isSpReportRes = repResourceName != null; boolean isJRReportRes = false; try { data = FileUtils.readFileToString(importFile); isJRReportRes = isJasperReport(data); } catch (Exception ex) { ex.printStackTrace(); edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ResourceImportExportDlg.class, ex); return; } boolean isReportRes = isJRReportRes || isSpReportRes; if (tabbedPane.getSelectedComponent() == viewsPanel) { int viewIndex = viewSetsList.getSelectedIndex(); if (viewIndex > -1) { boolean isAddItemForImport = viewSetsList.getSelectedValue() instanceof String; boolean isOK = false; SpViewSetObj vso = null; DataProviderSessionIFace session = null; try { session = DataProviderFactory.getInstance().createSession(); session.beginTransaction(); if (!isAddItemForImport) { vso = (SpViewSetObj) viewSetsList.getSelectedValue(); SpAppResourceDir appResDir = vso.getSpAppResourceDir(); importedName = vso.getName(); if (vso.getSpViewSetObjId() == null) { appResDir.getSpPersistedViewSets().add(vso); vso.setSpAppResourceDir(appResDir); } vso.setDataAsString(data, true); session.saveOrUpdate(appResDir); } else { SpAppResourceDir appResDir = dirs.get(levelIndex); vso = new SpViewSetObj(); vso.initialize(); vso.setLevel((short) levelIndex); vso.setName(FilenameUtils.getBaseName(importFile.getName())); appResDir.getSpPersistedViewSets().add(vso); vso.setSpAppResourceDir(appResDir); vso.setDataAsString(data); session.saveOrUpdate(appResDir); } session.saveOrUpdate(vso); for (SpAppResourceData ard : vso.getSpAppResourceDatas()) { session.saveOrUpdate(ard); } session.commit(); session.flush(); setHasChanged(true); isOK = true; completeMsg = getLocalizedMessage("RIE_RES_IMPORTED", importedName == null ? fileName : importedName); } catch (Exception ex) { ex.printStackTrace(); edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance() .capture(ResourceImportExportDlg.class, ex); session.rollback(); } finally { try { session.close(); } catch (Exception ex) { ex.printStackTrace(); edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance() .capture(ResourceImportExportDlg.class, ex); } } if (isOK) { if (isAddItemForImport) { viewSetsModel.clear(); viewSetsModel.addElement(vso); } else { viewSetsModel.remove(viewIndex); viewSetsModel.insertElementAt(vso, viewIndex); } viewSetsList.repaint(); } } } else { boolean isResourcePanel = tabbedPane.getSelectedComponent() == repPanel; JList theList = isResourcePanel ? repList : resList; int resIndex = theList.getSelectedIndex(); Object selObj = theList.getSelectedValue(); if (resIndex > -1) { if (resIndex == 0) // means we are adding a new resource { try { SpecifyUser user = contextMgr.getClassObject(SpecifyUser.class); Agent agent = contextMgr.getClassObject(Agent.class); SpAppResourceDir dir = dirs.get(levelIndex); SpAppResource appRes = new SpAppResource(); appRes.initialize(); appRes.setName(fileName); appRes.setCreatedByAgent(agent); appRes.setSpecifyUser(user); if (dir.getId() == null) { dir.mergeTransientResourceAndViewSets(); } Pair<SpAppResource, String> retValues = checkForOverwriteOrNewName(dir, isSpReportRes ? repResourceName : fileName, isSpReportRes); if (retValues != null && retValues.first == null && retValues.second == null) { return; // Dialog was Cancelled } SpAppResource fndAppRes = retValues != null && retValues.first != null ? retValues.first : null; String newResName = retValues != null && retValues.second != null ? retValues.second : null; if (isReportRes) { if (fndAppRes != null) { if (isSpReportRes) { ReportsBaseTask.deleteReportAndResource(null, fndAppRes.getId()); } else { //XXX ??????????? if (fndAppRes.getSpAppResourceId() != null) { contextMgr.removeAppResourceSp(fndAppRes.getSpAppResourceDir(), fndAppRes); } } } /*else if (newResName == null) { return; }*/ if (isSpReportRes) { appRes = importSpReportZipResource(importFile, appRes, dir, newResName); if (appRes != null) { importedName = appRes.getName(); } } else { if (MainFrameSpecify.importJasperReport(importFile, false, newResName)) { importedName = importFile.getName(); } else { return; } } if (importedName != null) { CommandDispatcher.dispatch(new CommandAction(ReportsBaseTask.REPORTS, ReportsBaseTask.REFRESH, null)); CommandDispatcher.dispatch(new CommandAction(QueryTask.QUERY, QueryTask.REFRESH_QUERIES, null)); levelSelected(); } } else if (fndAppRes != null) // overriding { appRes.setMetaData(fndAppRes.getMetaData()); appRes.setDescription(fndAppRes.getDescription()); appRes.setFileName(fileName); appRes.setMimeType(appRes.getMimeType()); appRes.setName(fileName); appRes.setLevel(fndAppRes.getLevel()); } else if (!getMetaInformation(appRes, fileName)) { return; } if (!isReportRes) { appRes.setSpAppResourceDir(dir); dir.getSpAppResources().add(appRes); appRes.setDataAsString(data); contextMgr.saveResource(appRes); completeMsg = getLocalizedMessage("RIE_RES_IMPORTED", importedName == null ? fileName : importedName); } setHasChanged(true); } catch (Exception e) { e.printStackTrace(); edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance() .capture(ResourceImportExportDlg.class, e); } } else if (selObj instanceof AppResourceIFace) { //if (isResourcePanel) resIndex++; AppResourceIFace fndAppRes = null; for (AppResourceIFace appRes : resources) { if (appRes == selObj) { fndAppRes = appRes; break; } } if (fndAppRes != null) { String importedFileName = fndAppRes.getFileName(); String fName = FilenameUtils.getName(importedFileName); String dbBaseName = FilenameUtils.getBaseName(fileName); //log.debug("["+fName+"]["+dbBaseName+"]"); boolean doOverwrite = true; if (!dbBaseName.equals(fName)) { String msg = getLocalizedMessage("RIE_OVRDE_MSG", dbBaseName, fName); doOverwrite = displayConfirm(getResourceString("RIE_OVRDE_TITLE"), msg, getResourceString("RIE_OVRDE"), getResourceString("CANCEL"), JOptionPane.QUESTION_MESSAGE); } if (doOverwrite) { fndAppRes.setDataAsString(data); contextMgr.saveResource(fndAppRes); completeMsg = getLocalizedMessage("RIE_RES_IMPORTED", importedName == null ? fileName : importedName); } } else { UIRegistry.showError("Strange error - Couldn't resource."); } } } } if (importedName != null) { completeMsg = getLocalizedMessage("RIE_RES_IMPORTED", importedName == null ? fileName : importedName); } if (hasChanged()) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { okBtn.doClick(); } }); } } else { UIRegistry.showLocalizedError("FILE_NO_EXISTS", fullFileName); } } enableUI(); } }
From source file:de.huxhorn.lilith.swing.MainFrame.java
public void open(File dataFile) { if (logger.isInfoEnabled()) logger.info("Open file: {}", dataFile.getAbsolutePath()); if (!dataFile.isFile()) { String message = "'" + dataFile.getAbsolutePath() + "' is not a file!"; JOptionPane.showMessageDialog(this, message, "Can't open file...", JOptionPane.ERROR_MESSAGE); return;/*from w w w . j av a 2 s .co m*/ } if (!dataFile.canRead()) { String message = "Can't read from '" + dataFile.getAbsolutePath() + "'!"; JOptionPane.showMessageDialog(this, message, "Can't open file...", JOptionPane.ERROR_MESSAGE); return; } ViewContainer<?> viewContainer = resolveViewContainer(dataFile); if (viewContainer != null) { showView(viewContainer); String message = "File '" + dataFile.getAbsolutePath() + "' is already open."; JOptionPane.showMessageDialog(this, message, "File is already open...", JOptionPane.INFORMATION_MESSAGE); return; } String fileName = dataFile.getAbsolutePath(); String indexFileName; if (fileName.toLowerCase().endsWith(FileConstants.FILE_EXTENSION)) { indexFileName = fileName.substring(0, fileName.length() - FileConstants.FILE_EXTENSION.length()); } else { indexFileName = fileName; } indexFileName = indexFileName + FileConstants.INDEX_FILE_EXTENSION; long dataModified = dataFile.lastModified(); File indexFile = new File(indexFileName); if (!indexFile.isFile()) { // Index file does not exist. Ask if it should be indexed. String dialogTitle = "Index file?"; String message = "Index file does not exist!\nIndex data file right now?"; int result = JOptionPane.showConfirmDialog(this, message, dialogTitle, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (JOptionPane.OK_OPTION != result) { // file will not be opened. return; } String name = "Indexing Lilith file"; String description = "Indexing '" + dataFile.getAbsolutePath() + "'..."; Task<Long> task = longTaskManager.startTask(new IndexingCallable(dataFile, indexFile), name, description); if (logger.isInfoEnabled()) logger.info("Task-Name: {}", task.getName()); // opening of view will be done by the task return; } // Previous index file was found long indexModified = indexFile.lastModified(); if (indexModified < dataModified) { // Index file is outdated. Ask if it should be reindexed. String dialogTitle = "Index outdated. Reindex file?"; String message = "The index file is older than the data file!\nReindex data file right now?"; int result = JOptionPane.showConfirmDialog(this, message, dialogTitle, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (JOptionPane.OK_OPTION == result) { if (indexFile.delete()) { if (logger.isInfoEnabled()) logger.info("Deleted previous index file {}.", indexFile.getAbsolutePath()); String name = "Reindexing Lilith file"; String description = "Reindexing '" + dataFile.getAbsolutePath() + "'..."; Task<Long> task = longTaskManager.startTask(new IndexingCallable(dataFile, indexFile), name, description); if (logger.isInfoEnabled()) logger.info("Task-Name: {}", task.getName()); // opening of view will be done by the task return; } } // It's fine to use the outdated index. } // use existing index file createViewFor(dataFile, indexFile, true); }
From source file:marytts.tools.redstart.AdminWindow.java
private void jMenuItem_ImportTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_ImportTextActionPerformed JFileChooser fc = new JFileChooser(new File(voiceFolderPathString)); fc.setDialogTitle("Choose text file to import"); //fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int returnVal = fc.showOpenDialog(this); if (returnVal != JFileChooser.APPROVE_OPTION) return;/* w w w . j a va2 s . com*/ File file = fc.getSelectedFile(); if (file == null) return; String[] lines = null; try { lines = StringUtils.readTextFile(file.getAbsolutePath(), "UTF-8"); } catch (IOException ioe) { ioe.printStackTrace(); } if (lines == null || lines.length == 0) return; Object[] options = new Object[] { "Keep first column", "Discard first column" }; int answer = JOptionPane.showOptionDialog(this, "File contains " + lines.length + " sentences.\n" + "Sample line:\n" + lines[0] + "\n" + "Keep or discard first column?", "Import details", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); boolean discardFirstColumn = (answer == JOptionPane.NO_OPTION); String prefix = (String) JOptionPane.showInputDialog(this, "Prefix to use for individual sentence filenames:", "Choose filename prefix", JOptionPane.PLAIN_MESSAGE, null, null, "s"); int numDigits = (int) Math.log10(lines.length) + 1; String pattern = prefix + "%0" + numDigits + "d.txt"; File scriptFile = new File(voiceFolderPathString + "/" + file.getName() + ".script.txt"); PrintWriter scriptWriter = null; try { scriptWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(scriptFile), "UTF-8")); } catch (IOException e) { JOptionPane.showMessageDialog(this, "Cannot write to script file " + scriptFile.getAbsolutePath() + ":\n" + e.getMessage()); if (scriptWriter != null) scriptWriter.close(); return; } File textFolder = getPromptFolderPath(); // if filename ends with ".txt_tr" then it has also transcriptions in it String selectedFile_ext = FilenameUtils.getExtension(file.getName()); Boolean inputHasAlsoTranscription = false; File transcriptionFolder = new File(""); // transcription folder name, and makedir if (selectedFile_ext.equals("txt_tr")) { System.out.println("txt_tr"); if (lines.length % 2 == 0) { // even } else { // odd System.err.println(".txt_tr file has an odd number of lines, so it's corrupted, exiting."); System.exit(0); } inputHasAlsoTranscription = true; String transcriptionFolderName = voiceFolderPathString + AdminWindow.TRANSCRIPTION_FOLDER_NAME; transcriptionFolder = new File(transcriptionFolderName); if (transcriptionFolder.exists()) { System.out.println("transcription folder already exists"); } else { if (transcriptionFolder.mkdirs()) { System.out.println("transcription folder created"); } else { System.err.println("Cannot create transcription folder -- exiting."); System.exit(0); } } } else { System.out.println("input file extension is not txt_tr, but " + selectedFile_ext + ", so it contains ortographic sentences without transcriptions."); } for (int i = 0; i < lines.length; i++) { String line = lines[i]; if (discardFirstColumn) line = line.substring(line.indexOf(' ') + 1); int sent_index = i + 1; if (inputHasAlsoTranscription == true) { sent_index = i / 2 + 1; } String filename = String.format(pattern, sent_index); System.out.println(filename + " " + line); File textFile = new File(textFolder, filename); if (textFile.exists()) { JOptionPane.showMessageDialog(this, "Cannot writing file " + filename + ":\n" + "File exists!\n" + "Aborting text file import."); return; } PrintWriter pw = null; try { pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(textFile), "UTF-8")); pw.println(line); scriptWriter.println(filename.substring(0, filename.lastIndexOf('.')) + " " + line); } catch (IOException ioe) { JOptionPane.showMessageDialog(this, "Error writing file " + filename + ":\n" + ioe.getMessage()); ioe.printStackTrace(); return; } finally { if (pw != null) pw.close(); } // transcription case: if (inputHasAlsoTranscription == true) { // modify pattern: best would be something like sed "s/.txt$/.tr$/" // easy but dirty: String transc_pattern = pattern.replace(".txt", ".tr"); filename = String.format(transc_pattern, sent_index); i++; line = lines[i]; if (discardFirstColumn) line = line.substring(line.indexOf(' ') + 1); File transcriptionTextFile = new File(transcriptionFolder, filename); if (transcriptionTextFile.exists()) { JOptionPane.showMessageDialog(this, "Cannot writing file " + transcriptionTextFile.getName() + ":\n" + "File exists!\n" + "Aborting text file import."); return; } pw = null; try { pw = new PrintWriter( new OutputStreamWriter(new FileOutputStream(transcriptionTextFile), "UTF-8")); pw.println(line); scriptWriter.println(filename.substring(0, filename.lastIndexOf('.')) + " " + line); } catch (IOException ioe) { JOptionPane.showMessageDialog(this, "Error writing file " + filename + ":\n" + ioe.getMessage()); ioe.printStackTrace(); return; } finally { if (pw != null) pw.close(); } } } scriptWriter.close(); setupVoice(); }