List of usage examples for javax.swing JFileChooser showOpenDialog
public int showOpenDialog(Component parent) throws HeadlessException
From source file:com.floreantpos.ui.model.PizzaItemForm.java
private void doSelectImageFile() { JFileChooser fileChooser = new JFileChooser(); fileChooser.setMultiSelectionEnabled(false); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); int option = fileChooser.showOpenDialog(POSUtil.getBackOfficeWindow()); if (option == JFileChooser.APPROVE_OPTION) { File imageFile = fileChooser.getSelectedFile(); try {//from ww w .ja v a 2s . c om byte[] itemImage = FileUtils.readFileToByteArray(imageFile); int imageSize = itemImage.length / 1024; if (imageSize > 20) { POSMessageDialog.showMessage(Messages.getString("MenuItemForm.0")); //$NON-NLS-1$ itemImage = null; return; } ImageIcon imageIcon = new ImageIcon( new ImageIcon(itemImage).getImage().getScaledInstance(80, 80, Image.SCALE_SMOOTH)); lblImagePreview.setIcon(imageIcon); MenuItem menuItem = (MenuItem) getBean(); menuItem.setImageData(itemImage); } catch (IOException e) { PosLog.error(getClass(), e); } } }
From source file:techtonic.Techtonic.java
private void jmiLoadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmiLoadActionPerformed JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter fnef = new FileNameExtensionFilter("xml file only", ".xml"); chooser.setFileFilter(fnef);/* w ww .j a va2 s . co m*/ int input = chooser.showOpenDialog(this); if (input == 0) { } }
From source file:de.evaluationtool.gui.EvaluationFrameActionListener.java
private void loadReference() throws Exception { JFileChooser chooser = new JFileChooser("Please choose a reference file or directory."); chooser.setCurrentDirectory(frame.defaultDirectory); // TODO: detect if all directory formats are not readable and in this case dont allow directory opening chooser.setFileSelectionMode(/* www .ja v a2 s. co m*/ ReferenceFormats.REFERENCE_FORMATS.directoryFormats.isEmpty() ? JFileChooser.FILES_ONLY : JFileChooser.FILES_AND_DIRECTORIES); for (ReferenceFormat format : ReferenceFormats.REFERENCE_FORMATS.readableFormats) { chooser.addChoosableFileFilter( new FilesystemFilter(format.getFileExtension(), format.getDescription())); } chooser.setAcceptAllFileFilterUsed(true); int returnVal = chooser.showOpenDialog(frame); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } ReferenceFormat format = null; System.out.print("Loading..."); frame.setTitle("Loading..."); File f = chooser.getSelectedFile(); Collection<ReferenceFormat> formats; if (f.isDirectory()) { formats = ReferenceFormats.REFERENCE_FORMATS.directoryFormats; } else { formats = ReferenceFormats.REFERENCE_FORMATS.extensionToFormats .get(f.getName().substring(f.getName().lastIndexOf(".") + 1)); } if (formats == null || formats.isEmpty()) { throw new Exception("No format available that can read files with the " + f.getName().substring(f.getName().lastIndexOf(".") + 1) + " extension."); } if (formats.size() == 1) { format = formats.iterator().next(); } else { format = formatChooser(formats); } if (format == null) { return; } Reference reference = format.readReference(chooser.getSelectedFile(), true, frame.loadLimit); if (!reference.links.isEmpty()) { Link firstLink = reference.links.iterator().next(); frame.dataSourceName1 = EvaluationFrame.getProbableDatasourceName(firstLink.uris.first); frame.dataSourceName2 = EvaluationFrame.getProbableDatasourceName(firstLink.uris.second); } frame.setReference(reference); //frame.loadPositiveNegativeNT(chooser.getSelectedFile()); System.out.println("loading finished, " + reference.links.size() + " links loaded."); }
From source file:com.pingtel.sipviewer.SIPViewerFrame.java
protected String selectFile(JFrame parent, String strFilter, String strFilterDesc) { String fileName = null;//from ww w . ja va 2 s . c om if (m_fileChooserDir == null || m_fileChooserDir.length() < 1) { m_fileChooserDir = "."; } System.out.println("chooser dir: " + m_fileChooserDir); JFileChooser chooser = new JFileChooser(m_fileChooserDir); ExampleFileFilter filter = new ExampleFileFilter(); filter.addExtension(strFilter); filter.setDescription(strFilterDesc); chooser.setFileFilter(filter); int returnVal = chooser.showOpenDialog(parent); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); fileName = file.getAbsolutePath(); // Set the default directory for next time m_fileChooserDir = file.getParentFile().getAbsolutePath(); System.out.println("saving chooser dir: " + m_fileChooserDir); String fileNameNoPath = file.getName(); this.setTitle("SIP Viewer - " + fileNameNoPath); } return (fileName); }
From source file:de.codesourcery.eve.skills.ui.components.impl.MarketPriceEditorComponent.java
private void importMarketLogs() { File inputDir = null;/* w ww .j av a 2 s . c o m*/ if (appConfigProvider.getAppConfig().hasLastMarketLogImportDirectory()) { inputDir = appConfigProvider.getAppConfig().getLastMarketLogImportDirectory(); if (!inputDir.exists() || !inputDir.isDirectory()) { inputDir = null; } } final JFileChooser chooser = inputDir != null ? new JFileChooser(inputDir) : new JFileChooser(); chooser.setFileHidingEnabled(false); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setMultiSelectionEnabled(true); if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { File[] files = chooser.getSelectedFiles(); if (!ArrayUtils.isEmpty(files)) { appConfigProvider.getAppConfig().setLastMarketLogImportDirectory(files[0].getParentFile()); try { appConfigProvider.save(); } catch (IOException e) { log.error("importMarketLogs(): Failed to save configuration", e); } importMarketLogs(files); } } }
From source file:edu.ku.brc.specify.tasks.subpane.wb.ImageFrame.java
protected File askUserForImageFile() { ImageFilter imageFilter = new ImageFilter(); JFileChooser fileChooser = new JFileChooser( WorkbenchTask.getDefaultDirPath(WorkbenchTask.IMAGES_FILE_PATH)); fileChooser.setFileFilter(imageFilter); fileChooser.setDialogTitle(getResourceString("WB_CHOOSE_IMAGE")); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); int userAction = fileChooser.showOpenDialog(this); AppPreferences localPrefs = AppPreferences.getLocalPrefs(); // remember the directory the user was last in localPrefs.put(WorkbenchTask.IMAGES_FILE_PATH, fileChooser.getCurrentDirectory().getAbsolutePath()); if (userAction == JFileChooser.APPROVE_OPTION) { String fullPath = fileChooser.getSelectedFile().getAbsolutePath(); if (imageFilter.isImageFile(fullPath)) { return fileChooser.getSelectedFile(); }/*w ww.j a va 2 s.co m*/ } // if for any reason (user cancelled) we got to this point... return null; }
From source file:edu.synth.SynthHelper.java
public String openDialogFileChooser(String path, boolean dirOnly, String name, String button, String filterType) {/*from www. j a v a2s .co m*/ JFileChooser fileOpen = new JFileChooser(); if (!path.isEmpty()) fileOpen.setCurrentDirectory(new File(path)); else fileOpen.setCurrentDirectory(new File(".")); if (dirOnly) fileOpen.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); else { fileOpen.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); switch (filterType) { case "abn": FileFilter filter = new FileNameExtensionFilter("*.abn - Abundances file", "abn"); fileOpen.setFileFilter(filter); break; case "model": filter = new FileNameExtensionFilter("*.atl - Kurucz's format model file", "atl"); fileOpen.setFileFilter(filter); break; case "lns": filter = new FileNameExtensionFilter("*.lns - Lines file", "lns"); fileOpen.setFileFilter(filter); break; } } fileOpen.setDialogTitle(name); fileOpen.setApproveButtonText(button); int returnVal = fileOpen.showOpenDialog(fileOpen); if (returnVal == JFileChooser.APPROVE_OPTION) { File selectedPath = fileOpen.getSelectedFile(); if (selectedPath != null) return selectedPath.getAbsolutePath(); } return ""; }
From source file:au.com.jwatmuff.eventmanager.gui.main.LoadCompetitionWindow.java
private void loadBackupButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadBackupButtonActionPerformed File databaseStore = new File(Main.getWorkingDirectory(), "comps"); JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new FileNameExtensionFilter("Event Manager Files", "evm")); JPanel optionsPanel = new JPanel(); optionsPanel.setBorder(/*from www . java 2 s. c o m*/ new CompoundBorder(new EmptyBorder(0, 10, 0, 10), new TitledBorder("Load backup options"))); JCheckBox preserveIDCheckbox = new JCheckBox("Preserve competition ID"); optionsPanel.add(preserveIDCheckbox); chooser.setAccessory(optionsPanel); if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { /* input zip file */ File file = chooser.getSelectedFile(); /* construct output directory */ File dir = new File(databaseStore, file.getName()); int suffix = 0; while (dir.exists()) { suffix++; dir = new File(databaseStore, file.getName() + "_" + suffix); } /* unzip */ try { ZipUtils.unzipFile(dir, file); /* change id */ Properties props = new Properties(); FileReader fr = new FileReader(new File(dir, "info.dat")); props.load(fr); fr.close(); if (!preserveIDCheckbox.isSelected()) { props.setProperty("UUID", UUID.randomUUID().toString()); } props.setProperty("name", props.getProperty("name") + " - " + dateFormat.format(new Date())); FileWriter fw = new FileWriter(new File(dir, "info.dat")); props.store(fw, ""); fw.close(); /* update gui */ checkDatabasesExecutor.schedule(checkDatabasesTask, 0, TimeUnit.MILLISECONDS); } catch (Exception e) { GUIUtils.displayError(null, "Error while opening file: " + e.getMessage()); } } }
From source file:AltiConsole.AltiConsoleMainScreen.java
/** * Handles all the actions./*from ww w. j a va 2 s. c o m*/ * * @param e * the action event. */ public void actionPerformed(final ActionEvent e) { final Translator trans = Application.getTranslator(); if (e.getActionCommand().equals("EXIT")) { System.out.println("exit and disconnecting\n"); if (JOptionPane.showConfirmDialog(this, trans.get("AltiConsoleMainScreen.ClosingWindow"), trans.get("AltiConsoleMainScreen.ReallyClosing"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) { DisconnectFromAlti(); System.exit(0); } } else if (e.getActionCommand().equals("ABOUT")) { AboutDialog.showPreferences(AltiConsoleMainScreen.this); } // ERASE_FLIGHT else if (e.getActionCommand().equals("ERASE_FLIGHT")) { if (JOptionPane.showConfirmDialog(this, trans.get("AltiConsoleMainScreen.eraseAllflightData"), trans.get("AltiConsoleMainScreen.eraseAllflightDataTitle"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) { System.out.println("erasing flight\n"); ErasingFlight(); } } else if (e.getActionCommand().equals("RETRIEVE_FLIGHT")) { System.out.println("retrieving flight\n"); RetrievingFlight(); } else // SAVE_FLIGHT if (e.getActionCommand().equals("SAVE_FLIGHT")) { System.out.println("Saving current flight\n"); SavingFlight(); } else // RETRIEVE_ALTI_CFG if (e.getActionCommand().equals("RETRIEVE_ALTI_CFG")) { System.out.println("retrieving alti config\n"); AltiConfigData pAlticonfig = retrieveAltiConfig(); if (pAlticonfig != null) AltiConfigDlg.showPreferences(AltiConsoleMainScreen.this, pAlticonfig, Serial); } // LICENSE else if (e.getActionCommand().equals("LICENSE")) { LicenseDialog.showPreferences(AltiConsoleMainScreen.this); } // comPorts else if (e.getActionCommand().equals("comPorts")) { DisconnectFromAlti(); String currentPort; //e. currentPort = (String) comPorts.getSelectedItem(); if (Serial != null) Serial.searchForPorts(); System.out.println("We have a new selected value for comport\n"); comPorts.setSelectedItem(currentPort); } // UPLOAD_FIRMWARE else if (e.getActionCommand().equals("UPLOAD_FIRMWARE")) { System.out.println("upload firmware\n"); //make sure to disconnect first DisconnectFromAlti(); JFileChooser fc = new JFileChooser(); String hexfile = null; File startFile = new File(System.getProperty("user.dir")); //FileNameExtensionFilter filter; fc.setDialogTitle("Select firmware"); //fc.set fc.setCurrentDirectory(startFile); //fc.addChoosableFileFilter(new FileNameExtensionFilter("*.HEX", "hex")); fc.setFileFilter(new FileNameExtensionFilter("*.hex", "hex")); //fc.fil int action = fc.showOpenDialog(SwingUtilities.windowForComponent(this)); if (action == JFileChooser.APPROVE_OPTION) { hexfile = fc.getSelectedFile().getAbsolutePath(); } if (hexfile != null) { String exefile = UserPref.getAvrdudePath(); String conffile = UserPref.getAvrdudeConfigPath(); String opts = " -v -v -v -v -patmega328p -carduino -P\\\\.\\" + (String) this.comPorts.getSelectedItem() + " -b115200 -D -V "; String cmd = exefile + " -C" + conffile + opts + " -Uflash:w:" + hexfile + ":i"; System.out.println(cmd); try { Process p = Runtime.getRuntime().exec(cmd); AfficheurFlux fluxSortie = new AfficheurFlux(p.getInputStream(), this); AfficheurFlux fluxErreur = new AfficheurFlux(p.getErrorStream(), this); new Thread(fluxSortie).start(); new Thread(fluxErreur).start(); p.waitFor(); } catch (IOException e1) { e1.printStackTrace(); } catch (InterruptedException e2) { e2.printStackTrace(); } } } // ON_LINE_HELP else if (e.getActionCommand().equals("ON_LINE_HELP")) { Desktop d = Desktop.getDesktop(); System.out.println("Online help \n"); try { d.browse(new URI(trans.get("help.url"))); } catch (URISyntaxException e1) { System.out.println("Illegal URL: " + trans.get("help.url") + " " + e1.getMessage()); } catch (IOException e1) { System.out.println("Unable to launch browser: " + e1.getMessage()); } } }
From source file:edu.harvard.mcz.imagecapture.loader.JobVerbatimFieldLoad.java
@Override public void start() { startDateTime = new Date(); Singleton.getSingletonInstance().getJobList().addJob((RunnableJob) this); runStatus = RunStatus.STATUS_RUNNING; String selectedFilename = ""; if (file == null) { final JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); if (Singleton.getSingletonInstance().getProperties().getProperties() .getProperty(ImageCaptureProperties.KEY_LASTLOADPATH) != null) { fileChooser.setCurrentDirectory(new File(Singleton.getSingletonInstance().getProperties() .getProperties().getProperty(ImageCaptureProperties.KEY_LASTLOADPATH))); }/*from ww w.jav a2 s . c o m*/ int returnValue = fileChooser.showOpenDialog(Singleton.getSingletonInstance().getMainFrame()); if (returnValue == JFileChooser.APPROVE_OPTION) { file = fileChooser.getSelectedFile(); } } if (file != null) { log.debug("Selected file to load: " + file.getName() + "."); if (file.exists() && file.isFile() && file.canRead()) { // Save location Singleton.getSingletonInstance().getProperties().getProperties() .setProperty(ImageCaptureProperties.KEY_LASTLOADPATH, file.getPath()); selectedFilename = file.getName(); String[] headers = new String[] {}; CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(headers); int rows = 0; try { rows = readRows(file, csvFormat); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), "Unable to load data, file not found: " + e.getMessage(), "Error: File Not Found", JOptionPane.OK_OPTION); errors.append("File not found ").append(e.getMessage()).append("\n"); log.error(e.getMessage(), e); } catch (IOException e) { errors.append("Error loading csv format, trying tab delimited: ").append(e.getMessage()) .append("\n"); log.debug(e.getMessage()); try { // try reading as tab delimited format, if successful, use that format. CSVFormat tabFormat = CSVFormat.newFormat('\t').withIgnoreSurroundingSpaces(true) .withHeader(headers).withQuote('"'); rows = readRows(file, tabFormat); csvFormat = tabFormat; } catch (IOException e1) { errors.append("Error Loading data: ").append(e1.getMessage()).append("\n"); log.error(e.getMessage(), e1); } } try { Reader reader = new FileReader(file); CSVParser csvParser = new CSVParser(reader, csvFormat); Map<String, Integer> csvHeader = csvParser.getHeaderMap(); headers = new String[csvHeader.size()]; int i = 0; for (String header : csvHeader.keySet()) { headers[i++] = header; log.debug(header); } boolean okToRun = true; //TODO: Work picking/checking responsibility into a FieldLoaderWizard List<String> headerList = Arrays.asList(headers); if (!headerList.contains("barcode")) { log.error("Input file " + file.getName() + " header does not contain required field 'barcode'."); // no barcode field, we can't match the input to specimen records. errors.append("Field \"barcode\" not found in csv file headers. Unable to load data.") .append("\n"); okToRun = false; } if (okToRun) { Iterator<CSVRecord> iterator = csvParser.iterator(); FieldLoader fl = new FieldLoader(); if (headerList.size() == 3 && headerList.contains("verbatimUnclassifiedText") && headerList.contains("questions") && headerList.contains("barcode")) { log.debug("Input file matches case 1: Unclassified text only."); // Allowed case 1a: unclassified text only int confirm = JOptionPane.showConfirmDialog( Singleton.getSingletonInstance().getMainFrame(), "Confirm load from file " + selectedFilename + " (" + rows + " rows) with just barcode and verbatimUnclassifiedText", "Verbatim unclassified Field found for load", JOptionPane.OK_CANCEL_OPTION); if (confirm == JOptionPane.OK_OPTION) { String barcode = ""; int lineNumber = 0; while (iterator.hasNext()) { lineNumber++; counter.incrementSpecimens(); CSVRecord record = iterator.next(); try { String verbatimUnclassifiedText = record.get("verbatimUnclassifiedText"); barcode = record.get("barcode"); String questions = record.get("questions"); fl.load(barcode, verbatimUnclassifiedText, questions, true); counter.incrementSpecimensUpdated(); } catch (IllegalArgumentException e) { RunnableJobError error = new RunnableJobError(file.getName(), barcode, Integer.toString(lineNumber), e.getClass().getSimpleName(), e, RunnableJobError.TYPE_LOAD_FAILED); counter.appendError(error); log.error(e.getMessage(), e); } catch (LoadException e) { RunnableJobError error = new RunnableJobError(file.getName(), barcode, Integer.toString(lineNumber), e.getClass().getSimpleName(), e, RunnableJobError.TYPE_LOAD_FAILED); counter.appendError(error); log.error(e.getMessage(), e); } percentComplete = (int) ((lineNumber * 100f) / rows); this.setPercentComplete(percentComplete); } } else { errors.append("Load canceled by user.").append("\n"); } } else if (headerList.size() == 4 && headerList.contains("verbatimUnclassifiedText") && headerList.contains("questions") && headerList.contains("barcode") && headerList.contains("verbatimClusterIdentifier")) { log.debug( "Input file matches case 1: Unclassified text only (with cluster identifier)."); // Allowed case 1b: unclassified text only (including cluster identifier) int confirm = JOptionPane.showConfirmDialog( Singleton.getSingletonInstance().getMainFrame(), "Confirm load from file " + selectedFilename + " (" + rows + " rows) with just barcode and verbatimUnclassifiedText", "Verbatim unclassified Field found for load", JOptionPane.OK_CANCEL_OPTION); if (confirm == JOptionPane.OK_OPTION) { String barcode = ""; int lineNumber = 0; while (iterator.hasNext()) { lineNumber++; counter.incrementSpecimens(); CSVRecord record = iterator.next(); try { String verbatimUnclassifiedText = record.get("verbatimUnclassifiedText"); String verbatimClusterIdentifier = record.get("verbatimClusterIdentifier"); barcode = record.get("barcode"); String questions = record.get("questions"); fl.load(barcode, verbatimUnclassifiedText, verbatimClusterIdentifier, questions, true); counter.incrementSpecimensUpdated(); } catch (IllegalArgumentException e) { RunnableJobError error = new RunnableJobError(file.getName(), barcode, Integer.toString(lineNumber), e.getClass().getSimpleName(), e, RunnableJobError.TYPE_LOAD_FAILED); counter.appendError(error); log.error(e.getMessage(), e); } catch (LoadException e) { RunnableJobError error = new RunnableJobError(file.getName(), barcode, Integer.toString(lineNumber), e.getClass().getSimpleName(), e, RunnableJobError.TYPE_LOAD_FAILED); counter.appendError(error); log.error(e.getMessage(), e); } percentComplete = (int) ((lineNumber * 100f) / rows); this.setPercentComplete(percentComplete); } } else { errors.append("Load canceled by user.").append("\n"); } } else if (headerList.size() == 8 && headerList.contains("verbatimUnclassifiedText") && headerList.contains("questions") && headerList.contains("barcode") && headerList.contains("verbatimLocality") && headerList.contains("verbatimDate") && headerList.contains("verbatimNumbers") && headerList.contains("verbatimCollector") && headerList.contains("verbatimCollection")) { // Allowed case two, transcription into verbatim fields, must be exact list of all // verbatim fields, not including cluster identifier or other metadata. log.debug("Input file matches case 2: Full list of verbatim fields."); int confirm = JOptionPane.showConfirmDialog( Singleton.getSingletonInstance().getMainFrame(), "Confirm load from file " + selectedFilename + " (" + rows + " rows) with just barcode and verbatim fields.", "Verbatim Fields found for load", JOptionPane.OK_CANCEL_OPTION); if (confirm == JOptionPane.OK_OPTION) { String barcode = ""; int lineNumber = 0; while (iterator.hasNext()) { lineNumber++; counter.incrementSpecimens(); CSVRecord record = iterator.next(); try { String verbatimLocality = record.get("verbatimLocality"); String verbatimDate = record.get("verbatimDate"); String verbatimCollector = record.get("verbatimCollector"); String verbatimCollection = record.get("verbatimCollection"); String verbatimNumbers = record.get("verbatimNumbers"); String verbatimUnclasifiedText = record.get("verbatimUnclassifiedText"); barcode = record.get("barcode"); String questions = record.get("questions"); fl.load(barcode, verbatimLocality, verbatimDate, verbatimCollector, verbatimCollection, verbatimNumbers, verbatimUnclasifiedText, questions); counter.incrementSpecimensUpdated(); } catch (IllegalArgumentException e) { RunnableJobError error = new RunnableJobError(file.getName(), barcode, Integer.toString(lineNumber), e.getClass().getSimpleName(), e, RunnableJobError.TYPE_LOAD_FAILED); counter.appendError(error); log.error(e.getMessage(), e); } catch (LoadException e) { RunnableJobError error = new RunnableJobError(file.getName(), barcode, Integer.toString(lineNumber), e.getClass().getSimpleName(), e, RunnableJobError.TYPE_LOAD_FAILED); counter.appendError(error); log.error(e.getMessage(), e); } percentComplete = (int) ((lineNumber * 100f) / rows); this.setPercentComplete(percentComplete); } } else { errors.append("Load canceled by user.").append("\n"); } } else { // allowed case three, transcription into arbitrary sets verbatim or other fields log.debug("Input file case 3: Arbitrary set of fields."); // Check column headers before starting run. boolean headersOK = false; try { HeaderCheckResult headerCheck = fl.checkHeaderList(headerList); if (headerCheck.isResult()) { int confirm = JOptionPane.showConfirmDialog( Singleton.getSingletonInstance().getMainFrame(), "Confirm load from file " + selectedFilename + " (" + rows + " rows) with headers: \n" + headerCheck.getMessage().replaceAll(":", ":\n"), "Fields found for load", JOptionPane.OK_CANCEL_OPTION); if (confirm == JOptionPane.OK_OPTION) { headersOK = true; } else { errors.append("Load canceled by user.").append("\n"); } } else { int confirm = JOptionPane.showConfirmDialog( Singleton.getSingletonInstance().getMainFrame(), "Problem found with headers in file, try to load anyway?\nHeaders: \n" + headerCheck.getMessage().replaceAll(":", ":\n"), "Problem in fields for load", JOptionPane.OK_CANCEL_OPTION); if (confirm == JOptionPane.OK_OPTION) { headersOK = true; } else { errors.append("Load canceled by user.").append("\n"); } } } catch (LoadException e) { errors.append("Error loading data: \n").append(e.getMessage()).append("\n"); JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), e.getMessage().replaceAll(":", ":\n"), "Error Loading Data: Problem Fields", JOptionPane.ERROR_MESSAGE); log.error(e.getMessage(), e); } if (headersOK) { int lineNumber = 0; while (iterator.hasNext()) { lineNumber++; Map<String, String> data = new HashMap<String, String>(); CSVRecord record = iterator.next(); String barcode = record.get("barcode"); Iterator<String> hi = headerList.iterator(); boolean containsNonVerbatim = false; while (hi.hasNext()) { String header = hi.next(); // Skip any fields prefixed by the underscore character _ if (!header.equals("barcode") && !header.startsWith("_")) { data.put(header, record.get(header)); if (!header.equals("questions") && MetadataRetriever.isFieldExternallyUpdatable(Specimen.class, header) && MetadataRetriever.isFieldVerbatim(Specimen.class, header)) { containsNonVerbatim = true; } } } if (data.size() > 0) { try { boolean updated = false; if (containsNonVerbatim) { updated = fl.loadFromMap(barcode, data, WorkFlowStatus.STAGE_CLASSIFIED, true); } else { updated = fl.loadFromMap(barcode, data, WorkFlowStatus.STAGE_VERBATIM, true); } counter.incrementSpecimens(); if (updated) { counter.incrementSpecimensUpdated(); } } catch (HibernateException e1) { // Catch (should just be development) problems with the underlying query StringBuilder message = new StringBuilder(); message.append("Query Error loading row (").append(lineNumber) .append(")[").append(barcode).append("]") .append(e1.getMessage()); RunnableJobError err = new RunnableJobError(selectedFilename, barcode, Integer.toString(lineNumber), e1.getMessage(), e1, RunnableJobError.TYPE_LOAD_FAILED); counter.appendError(err); log.error(e1.getMessage(), e1); } catch (LoadException e) { StringBuilder message = new StringBuilder(); message.append("Error loading row (").append(lineNumber).append(")[") .append(barcode).append("]").append(e.getMessage()); RunnableJobError err = new RunnableJobError(selectedFilename, barcode, Integer.toString(lineNumber), e.getMessage(), e, RunnableJobError.TYPE_LOAD_FAILED); counter.appendError(err); // errors.append(message.append("\n").toString()); log.error(e.getMessage(), e); } } percentComplete = (int) ((lineNumber * 100f) / rows); this.setPercentComplete(percentComplete); } } else { String message = "Can't load data, problem with headers."; errors.append(message).append("\n"); log.error(message); } } } csvParser.close(); reader.close(); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), "Unable to load data, file not found: " + e.getMessage(), "Error: File Not Found", JOptionPane.OK_OPTION); errors.append("File not found ").append(e.getMessage()).append("\n"); log.error(e.getMessage(), e); } catch (IOException e) { errors.append("Error Loading data: ").append(e.getMessage()).append("\n"); log.error(e.getMessage(), e); } } } else { //TODO: handle error condition log.error("File selection cancelled by user."); } report(selectedFilename); done(); }