List of usage examples for java.util Vector addAll
public boolean addAll(Collection<? extends E> c)
From source file:edu.ku.brc.specify.tasks.subpane.wb.WorkbenchPaneSS.java
/** * Constructs the pane for the spreadsheet. * /*from w w w .jav a2 s. c om*/ * @param name the name of the pane * @param task the owning task * @param workbench the workbench to be edited * @param showImageView shows image window when first showing the window */ public WorkbenchPaneSS(final String name, final Taskable task, final Workbench workbenchArg, final boolean showImageView, final boolean isReadOnly) throws Exception { super(name, task); removeAll(); if (workbenchArg == null) { return; } this.workbench = workbenchArg; this.isReadOnly = isReadOnly; headers.addAll(workbench.getWorkbenchTemplate().getWorkbenchTemplateMappingItems()); Collections.sort(headers); boolean hasOneOrMoreImages = false; // pre load all the data for (WorkbenchRow wbRow : workbench.getWorkbenchRows()) { for (WorkbenchDataItem wbdi : wbRow.getWorkbenchDataItems()) { wbdi.getCellData(); } if (wbRow.getWorkbenchRowImages() != null && wbRow.getWorkbenchRowImages().size() > 0) { hasOneOrMoreImages = true; } } model = new GridTableModel(this); spreadSheet = new WorkbenchSpreadSheet(model, this); spreadSheet.setReadOnly(isReadOnly); model.setSpreadSheet(spreadSheet); Highlighter simpleStriping = HighlighterFactory.createSimpleStriping(); GridCellHighlighter hl = new GridCellHighlighter( new GridCellPredicate(GridCellPredicate.AnyPredicate, null)); Short[] errs = { WorkbenchDataItem.VAL_ERROR, WorkbenchDataItem.VAL_ERROR_EDIT }; ColorHighlighter errColorHighlighter = new ColorHighlighter( new GridCellPredicate(GridCellPredicate.ValidationPredicate, errs), CellRenderingAttributes.errorBackground, null); Short[] newdata = { WorkbenchDataItem.VAL_NEW_DATA }; ColorHighlighter noDataHighlighter = new ColorHighlighter( new GridCellPredicate(GridCellPredicate.MatchingPredicate, newdata), CellRenderingAttributes.newDataBackground, null); Short[] multimatch = { WorkbenchDataItem.VAL_MULTIPLE_MATCH }; ColorHighlighter multiMatchHighlighter = new ColorHighlighter( new GridCellPredicate(GridCellPredicate.MatchingPredicate, multimatch), CellRenderingAttributes.multipleMatchBackground, null); spreadSheet.setHighlighters(simpleStriping, hl, errColorHighlighter, noDataHighlighter, multiMatchHighlighter); //add key mappings for cut, copy, paste //XXX Note: these are shortcuts directly to the SpreadSheet cut,copy,paste methods, NOT to the Specify edit menu. addRecordKeyMappings(spreadSheet, KeyEvent.VK_C, "Copy", new AbstractAction() { public void actionPerformed(ActionEvent ae) { SwingUtilities.invokeLater(new Runnable() { /* (non-Javadoc) * @see java.lang.Runnable#run() */ @Override public void run() { spreadSheet.cutOrCopy(false); } }); } }, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); addRecordKeyMappings(spreadSheet, KeyEvent.VK_X, "Cut", new AbstractAction() { public void actionPerformed(ActionEvent ae) { SwingUtilities.invokeLater(new Runnable() { /* (non-Javadoc) * @see java.lang.Runnable#run() */ @Override public void run() { spreadSheet.cutOrCopy(true); } }); } }, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); addRecordKeyMappings(spreadSheet, KeyEvent.VK_V, "Paste", new AbstractAction() { public void actionPerformed(ActionEvent ae) { SwingUtilities.invokeLater(new Runnable() { /* (non-Javadoc) * @see java.lang.Runnable#run() */ @Override public void run() { spreadSheet.paste(); } }); } }, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); findPanel = spreadSheet.getFindReplacePanel(); UIRegistry.getLaunchFindReplaceAction().setSearchReplacePanel(findPanel); spreadSheet.setShowGrid(true); JTableHeader header = spreadSheet.getTableHeader(); header.addMouseListener(new ColumnHeaderListener()); header.setReorderingAllowed(false); // Turn Off column dragging // Put the model in image mode, and never change it. // Now we're showing/hiding the image column using JXTable's column hiding features. model.setInImageMode(true); int imageColIndex = model.getColumnCount() - 1; imageColExt = spreadSheet.getColumnExt(imageColIndex); imageColExt.setVisible(false); int sgrColIndex = model.getSgrHeading().getViewOrder(); sgrColExt = spreadSheet.getColumnExt(sgrColIndex); sgrColExt.setComparator(((WorkbenchSpreadSheet) spreadSheet).new NumericColumnComparator()); int cmpIdx = 0; for (Comparator<String> cmp : ((WorkbenchSpreadSheet) spreadSheet).getComparators()) { if (cmp != null) { spreadSheet.getColumnExt(cmpIdx++).setComparator(cmp); } } // Start off with the SGR score column hidden showHideSgrCol(false); model.addTableModelListener(new TableModelListener() { public void tableChanged(TableModelEvent e) { setChanged(true); } }); spreadSheet.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { UIRegistry.enableCutCopyPaste(true); UIRegistry.enableFind(findPanel, true); } @Override public void focusLost(FocusEvent e) { UIRegistry.enableCutCopyPaste(true); UIRegistry.enableFind(findPanel, true); } }); if (isReadOnly) { saveBtn = null; } else { saveBtn = createButton(getResourceString("SAVE")); saveBtn.setToolTipText( String.format(getResourceString("WB_SAVE_DATASET_TT"), new Object[] { workbench.getName() })); saveBtn.setEnabled(false); saveBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { UsageTracker.incrUsageCount("WB.SaveDataSet"); UIRegistry.writeSimpleGlassPaneMsg( String.format(getResourceString("WB_SAVING"), new Object[] { workbench.getName() }), WorkbenchTask.GLASSPANE_FONT_SIZE); UIRegistry.getStatusBar().setIndeterminate(workbench.getName(), true); final SwingWorker worker = new SwingWorker() { @SuppressWarnings("synthetic-access") @Override public Object construct() { try { saveObject(); } catch (Exception ex) { UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(WorkbenchPaneSS.class, ex); log.error(ex); return ex; } return null; } // Runs on the event-dispatching thread. @Override public void finished() { Object retVal = get(); if (retVal != null && retVal instanceof Exception) { Exception ex = (Exception) retVal; UIRegistry.getStatusBar().setErrorMessage(getResourceString("WB_ERROR_SAVING"), ex); } UIRegistry.clearSimpleGlassPaneMsg(); UIRegistry.getStatusBar().setProgressDone(workbench.getName()); } }; worker.start(); } }); } Action delAction = addRecordKeyMappings(spreadSheet, KeyEvent.VK_F3, "DelRow", new AbstractAction() { public void actionPerformed(ActionEvent ae) { if (validationWorkerQueue.peek() == null) { deleteRows(); } } }, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); if (isReadOnly) { deleteRowsBtn = null; } else { deleteRowsBtn = createIconBtn("DelRec", "WB_DELETE_ROW", delAction); selectionSensitiveButtons.add(deleteRowsBtn); spreadSheet.setDeleteAction(delAction); } //XXX Using the wb ID in the prefname to do pref setting per wb, may result in a bloated prefs file?? doIncrementalValidation = AppPreferences.getLocalPrefs() .getBoolean(wbAutoValidatePrefName + "." + workbench.getId(), true); doIncrementalMatching = AppPreferences.getLocalPrefs() .getBoolean(wbAutoMatchPrefName + "." + workbench.getId(), false); if (isReadOnly) { clearCellsBtn = null; } else { clearCellsBtn = createIconBtn("Eraser", "WB_CLEAR_CELLS", new ActionListener() { public void actionPerformed(ActionEvent ae) { spreadSheet.clearSorter(); if (spreadSheet.getCellEditor() != null) { spreadSheet.getCellEditor().stopCellEditing(); } int[] rows = spreadSheet.getSelectedRowModelIndexes(); int[] cols = spreadSheet.getSelectedColumnModelIndexes(); model.clearCells(rows, cols); } }); selectionSensitiveButtons.add(clearCellsBtn); } Action addAction = addRecordKeyMappings(spreadSheet, KeyEvent.VK_N, "AddRow", new AbstractAction() { public void actionPerformed(ActionEvent ae) { if (workbench.getWorkbenchRows().size() < WorkbenchTask.MAX_ROWS) { if (validationWorkerQueue.peek() == null) { addRowAfter(); } } } }, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); if (isReadOnly) { addRowsBtn = null; } else { addRowsBtn = createIconBtn("AddRec", "WB_ADD_ROW", addAction); addRowsBtn.setEnabled(true); addAction.setEnabled(true); } if (isReadOnly) { carryForwardBtn = null; } else { carryForwardBtn = createIconBtn("CarryForward20x20", IconManager.IconSize.NonStd, "WB_CARRYFORWARD", false, new ActionListener() { public void actionPerformed(ActionEvent ae) { UsageTracker.getUsageCount("WBCarryForward"); configCarryFoward(); } }); carryForwardBtn.setEnabled(true); } toggleImageFrameBtn = createIconBtn("CardImage", IconManager.IconSize.NonStd, "WB_SHOW_IMG_WIN", false, new ActionListener() { public void actionPerformed(ActionEvent ae) { toggleImageFrameVisible(); } }); toggleImageFrameBtn.setEnabled(true); importImagesBtn = createIconBtn("CardImage", IconManager.IconSize.NonStd, "WB_SHOW_IMG_WIN", false, new ActionListener() { public void actionPerformed(ActionEvent ae) { toggleImportImageFrameVisible(); } }); importImagesBtn.setEnabled(true); /*showMapBtn = createIconBtn("ShowMap", IconManager.IconSize.NonStd, "WB_SHOW_MAP", false, new ActionListener() { public void actionPerformed(ActionEvent ae) { showMapOfSelectedRecords(); } });*/ // enable or disable along with Google Earth and Geo Ref Convert buttons if (isReadOnly) { exportKmlBtn = null; } else { exportKmlBtn = createIconBtn("GoogleEarth", IconManager.IconSize.NonStd, "WB_SHOW_IN_GOOGLE_EARTH", false, new ActionListener() { public void actionPerformed(ActionEvent ae) { SwingUtilities.invokeLater(new Runnable() { public void run() { showRecordsInGoogleEarth(); } }); } }); } // readRegisteries(); // enable or disable along with Show Map and Geo Ref Convert buttons if (isReadOnly) { geoRefToolBtn = null; } else { AppPreferences remotePrefs = AppPreferences.getRemote(); final String tool = remotePrefs.get("georef_tool", "geolocate"); String iconName = "GEOLocate20"; //tool.equalsIgnoreCase("geolocate") ? "GeoLocate" : "BioGeoMancer"; String toolTip = tool.equalsIgnoreCase("geolocate") ? "WB_DO_GEOLOCATE_LOOKUP" : "WB_DO_BIOGEOMANCER_LOOKUP"; geoRefToolBtn = createIconBtn(iconName, IconManager.IconSize.NonStd, toolTip, false, new ActionListener() { public void actionPerformed(ActionEvent ae) { spreadSheet.clearSorter(); if (tool.equalsIgnoreCase("geolocate")) { doGeoRef(new edu.ku.brc.services.geolocate.prototype.GeoCoordGeoLocateProvider(), "WB.GeoLocateRows"); } else { doGeoRef(new GeoCoordBGMProvider(), "WB.BioGeomancerRows"); } } }); // only enable it if the workbench has the proper columns in it String[] missingColumnsForBG = getMissingButRequiredColumnsForGeoRefTool(tool); if (missingColumnsForBG.length > 0) { geoRefToolBtn.setEnabled(false); String ttText = "<p>" + getResourceString("WB_ADDITIONAL_FIELDS_REQD") + ":<ul>"; for (String reqdField : missingColumnsForBG) { ttText += "<li>" + reqdField + "</li>"; } ttText += "</ul>"; String origTT = geoRefToolBtn.getToolTipText(); geoRefToolBtn.setToolTipText("<html>" + origTT + ttText); } else { geoRefToolBtn.setEnabled(true); } } if (isReadOnly) { convertGeoRefFormatBtn = null; } else { convertGeoRefFormatBtn = createIconBtn("ConvertGeoRef", IconManager.IconSize.NonStd, "WB_CONVERT_GEO_FORMAT", false, new ActionListener() { public void actionPerformed(ActionEvent ae) { showGeoRefConvertDialog(); } }); // now enable/disable the geo ref related buttons String[] missingGeoRefFields = getMissingGeoRefLatLonFields(); if (missingGeoRefFields.length > 0) { convertGeoRefFormatBtn.setEnabled(false); exportKmlBtn.setEnabled(false); //showMapBtn.setEnabled(false); String ttText = "<p>" + getResourceString("WB_ADDITIONAL_FIELDS_REQD") + ":<ul>"; for (String reqdField : missingGeoRefFields) { ttText += "<li>" + reqdField + "</li>"; } ttText += "</ul>"; String origTT1 = convertGeoRefFormatBtn.getToolTipText(); convertGeoRefFormatBtn.setToolTipText("<html>" + origTT1 + ttText); String origTT2 = exportKmlBtn.getToolTipText(); exportKmlBtn.setToolTipText("<html>" + origTT2 + ttText); //String origTT3 = showMapBtn.getToolTipText(); //showMapBtn.setToolTipText("<html>" + origTT3 + ttText); } else { convertGeoRefFormatBtn.setEnabled(true); exportKmlBtn.setEnabled(true); //showMapBtn.setEnabled(true); } } if (AppContextMgr.isSecurityOn() && !task.getPermissions().canModify()) { exportExcelCsvBtn = null; } else { exportExcelCsvBtn = createIconBtn("Export", IconManager.IconSize.NonStd, "WB_EXPORT_DATA", false, new ActionListener() { public void actionPerformed(ActionEvent ae) { doExcelCsvExport(); } }); exportExcelCsvBtn.setEnabled(true); } uploadDatasetBtn = createIconBtn("Upload", IconManager.IconSize.Std24, "WB_UPLOAD_DATA", false, new ActionListener() { public void actionPerformed(ActionEvent ae) { doDatasetUpload(); } }); uploadDatasetBtn.setVisible(isUploadPermitted() && !UIRegistry.isMobile()); uploadDatasetBtn.setEnabled(canUpload()); if (!uploadDatasetBtn.isEnabled()) { uploadDatasetBtn.setToolTipText(getResourceString("WB_UPLOAD_IN_PROGRESS")); } // listen to selection changes to enable/disable certain buttons spreadSheet.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { JStatusBar statusBar = UIRegistry.getStatusBar(); statusBar.setText(""); currentRow = spreadSheet.getSelectedRow(); updateBtnUI(); } } }); for (int c = 0; c < spreadSheet.getTableHeader().getColumnModel().getColumnCount(); c++) { // TableColumn column = // spreadSheet.getTableHeader().getColumnModel().getColumn(spreadSheet.getTableHeader().getColumnModel().getColumnCount()-1); TableColumn column = spreadSheet.getTableHeader().getColumnModel().getColumn(c); column.setCellRenderer(new WbCellRenderer()); } // setup the JFrame to show images attached to WorkbenchRows imageFrame = new ImageFrame(mapSize, this, this.workbench, task, isReadOnly); // setup the JFrame to show images attached to WorkbenchRows imageImportFrame = new ImageImportFrame(this, this.workbench); setupWorkbenchRowChangeListener(); // setup window minimizing/maximizing listener JFrame topFrame = (JFrame) UIRegistry.getTopWindow(); minMaxWindowListener = new WindowAdapter() { @Override public void windowDeiconified(WindowEvent e) { if (imageFrame != null && imageFrame.isVisible()) { imageFrame.setExtendedState(Frame.NORMAL); } if (mapFrame != null && mapFrame.isVisible()) { mapFrame.setExtendedState(Frame.NORMAL); } } @Override public void windowIconified(WindowEvent e) { if (imageFrame != null && imageFrame.isVisible()) { imageFrame.setExtendedState(Frame.ICONIFIED); } if (mapFrame != null && mapFrame.isVisible()) { mapFrame.setExtendedState(Frame.ICONIFIED); } } }; topFrame.addWindowListener(minMaxWindowListener); if (!isReadOnly) { showHideUploadToolBtn = createIconBtn("ValidateWB", IconManager.IconSize.NonStd, "WB_HIDE_UPLOADTOOLPANEL", false, new ActionListener() { public void actionPerformed(ActionEvent ae) { if (uploadToolPanel.isExpanded()) { hideUploadToolPanel(); showHideUploadToolBtn.setToolTipText(getResourceString("WB_SHOW_UPLOADTOOLPANEL")); } else { showUploadToolPanel(); showHideUploadToolBtn.setToolTipText(getResourceString("WB_HIDE_UPLOADTOOLPANEL")); } } }); showHideUploadToolBtn.setEnabled(true); } // setup the mapping features mapFrame = new JFrame(); mapFrame.setIconImage(IconManager.getImage("AppIcon").getImage()); mapFrame.setTitle(getResourceString("WB_GEO_REF_DATA_MAP")); mapImageLabel = createLabel(""); mapImageLabel.setSize(500, 500); mapFrame.add(mapImageLabel); mapFrame.setSize(500, 500); // start putting together the visible UI CellConstraints cc = new CellConstraints(); JComponent[] compsArray = { addRowsBtn, deleteRowsBtn, clearCellsBtn, /*showMapBtn,*/ exportKmlBtn, geoRefToolBtn, convertGeoRefFormatBtn, exportExcelCsvBtn, uploadDatasetBtn, showHideUploadToolBtn }; Vector<JComponent> availableComps = new Vector<JComponent>( compsArray.length + workBenchPluginSSBtns.size()); for (JComponent c : compsArray) { if (c != null) { availableComps.add(c); } } for (JComponent c : workBenchPluginSSBtns) { availableComps.add(c); } PanelBuilder spreadSheetControlBar = new PanelBuilder(new FormLayout( "f:p:g,4px," + createDuplicateJGoodiesDef("p", "4px", availableComps.size()) + ",4px,", "c:p:g")); int x = 3; for (JComponent c : availableComps) { spreadSheetControlBar.add(c, cc.xy(x, 1)); x += 2; } int h = 0; Vector<WorkbenchTemplateMappingItem> headers = new Vector<WorkbenchTemplateMappingItem>(); headers.addAll(workbench.getWorkbenchTemplate().getWorkbenchTemplateMappingItems()); Collections.sort(headers); for (WorkbenchTemplateMappingItem mi : headers) { //using the workbench data model table. Not the actual specify table the column is mapped to. //This MIGHT be less confusing //System.out.println("setting header renderer for " + mi.getTableName() + "." + mi.getFieldName()); spreadSheet.getColumnModel().getColumn(h++) .setHeaderRenderer(new WbTableHeaderRenderer(mi.getTableName())); } // NOTE: This needs to be done after the creation of the saveBtn. And after the creation of the header renderes. initColumnSizes(spreadSheet, saveBtn); // Create the Form Pane -- needs to be done after initColumnSizes - which also sets cell editors for collumns if (task instanceof SGRTask) { formPane = new SGRFormPane(this, workbench, isReadOnly); } else { formPane = new FormPane(this, workbench, isReadOnly); } // This panel contains just the ResultSetContoller, it's needed so the RSC gets centered PanelBuilder rsPanel = new PanelBuilder(new FormLayout("c:p:g", "c:p:g")); FormValidator dummy = new FormValidator(null); dummy.setEnabled(true); resultsetController = new ResultSetController(dummy, !isReadOnly, !isReadOnly, false, getResourceString("Record"), model.getRowCount(), true); resultsetController.addListener(formPane); if (!isReadOnly) { resultsetController.getDelRecBtn().addActionListener(delAction); } // else // { // resultsetController.getDelRecBtn().setVisible(false); // } rsPanel.add(resultsetController.getPanel(), cc.xy(1, 1)); // This panel is a single row containing the ResultSetContoller and the other controls for the Form Panel String colspec = "f:p:g, p, f:p:g, p"; for (int i = 0; i < workBenchPluginFormBtns.size(); i++) { colspec = colspec + ", f:p, p"; } PanelBuilder resultSetPanel = new PanelBuilder(new FormLayout(colspec, "c:p:g")); // Now put the two panel into the single row panel resultSetPanel.add(rsPanel.getPanel(), cc.xy(2, 1)); if (!isReadOnly) { resultSetPanel.add(formPane.getControlPropsBtn(), cc.xy(4, 1)); } int ccx = 6; for (JComponent c : workBenchPluginFormBtns) { resultSetPanel.add(c, cc.xy(ccx, 1)); ccx += 2; } // Create the main panel that uses card layout for the form and spreasheet mainPanel = new JPanel(cardLayout = new CardLayout()); // Add the Form and Spreadsheet to the CardLayout mainPanel.add(spreadSheet.getScrollPane(), PanelType.Spreadsheet.toString()); mainPanel.add(formPane.getPane(), PanelType.Form.toString()); // The controllerPane is a CardLayout that switches between the Spreadsheet control bar and the Form Control Bar controllerPane = new JPanel(cpCardLayout = new CardLayout()); controllerPane.add(spreadSheetControlBar.getPanel(), PanelType.Spreadsheet.toString()); controllerPane.add(resultSetPanel.getPanel(), PanelType.Form.toString()); JLabel sep1 = new JLabel(IconManager.getIcon("Separator")); JLabel sep2 = new JLabel(IconManager.getIcon("Separator")); ssFormSwitcher = createSwitcher(); // This works setLayout(new BorderLayout()); boolean doDnDImages = AppPreferences.getLocalPrefs().getBoolean("WB_DND_IMAGES", false); JComponent[] ctrlCompArray1 = { importImagesBtn, toggleImageFrameBtn, carryForwardBtn, sep1, saveBtn, sep2, ssFormSwitcher }; JComponent[] ctrlCompArray2 = { toggleImageFrameBtn, carryForwardBtn, sep1, saveBtn, sep2, ssFormSwitcher }; JComponent[] ctrlCompArray = doDnDImages ? ctrlCompArray1 : ctrlCompArray2; Vector<Pair<JComponent, Integer>> ctrlComps = new Vector<Pair<JComponent, Integer>>(); for (JComponent c : ctrlCompArray) { ctrlComps.add(new Pair<JComponent, Integer>(c, null)); } String layoutStr = ""; int compCount = 0; int col = 1; int pos = 0; for (Pair<JComponent, Integer> c : ctrlComps) { JComponent comp = c.getFirst(); if (comp != null) { boolean addComp = !(comp == sep1 || comp == sep2) || compCount > 0; if (!addComp) { c.setFirst(null); } else { if (!StringUtils.isEmpty(layoutStr)) { layoutStr += ","; col++; if (pos < ctrlComps.size() - 1) { //this works because we know ssFormSwitcher is last and always non-null. layoutStr += "6px,"; col++; } } c.setSecond(col); if (comp == sep1 || comp == sep2) { layoutStr += "6px"; compCount = 0; } else { layoutStr += "p"; compCount++; } } } pos++; } PanelBuilder ctrlBtns = new PanelBuilder(new FormLayout(layoutStr, "c:p:g")); for (Pair<JComponent, Integer> c : ctrlComps) { if (c.getFirst() != null) { ctrlBtns.add(c.getFirst(), cc.xy(c.getSecond(), 1)); } } add(mainPanel, BorderLayout.CENTER); FormLayout formLayout = new FormLayout("f:p:g,4px,p", "2px,f:p:g,p:g,p:g"); PanelBuilder builder = new PanelBuilder(formLayout); builder.add(controllerPane, cc.xy(1, 2)); builder.add(ctrlBtns.getPanel(), cc.xy(3, 2)); if (!isReadOnly) { uploadToolPanel = new UploadToolPanel(this, UploadToolPanel.EXPANDED); uploadToolPanel.createUI(); // showHideUploadToolBtn = createIconBtn("ValidateWB", IconManager.IconSize.NonStd, "WB_HIDE_UPLOADTOOLPANEL", false, new ActionListener() // { // public void actionPerformed(ActionEvent ae) // { // if (uploadToolPanel.isExpanded()) // { // hideUploadToolPanel(); // showHideUploadToolBtn.setToolTipText(getResourceString("WB_SHOW_UPLOADTOOLPANEL")); // } else // { // showUploadToolPanel(); // showHideUploadToolBtn.setToolTipText(getResourceString("WB_HIDE_UPLOADTOOLPANEL")); // } // } // }); // showHideUploadToolBtn.setEnabled(true); } builder.add(uploadToolPanel, cc.xywh(1, 3, 3, 1)); builder.add(findPanel, cc.xywh(1, 4, 3, 1)); add(builder.getPanel(), BorderLayout.SOUTH); resultsetController.addListener(new ResultSetControllerListener() { public boolean indexAboutToChange(int oldIndex, int newIndex) { return true; } public void indexChanged(int newIndex) { if (imageFrame != null) { if (newIndex > -1) { int index = spreadSheet.convertRowIndexToModel(newIndex); imageFrame.setRow(workbench.getRow(index)); } else { imageFrame.setRow(null); } } } public void newRecordAdded() { // do nothing } }); //compareSchemas(); if (getIncremental() && workbenchValidator == null) { buildValidator(); } // int c = 0; // Vector<WorkbenchTemplateMappingItem> headers = new Vector<WorkbenchTemplateMappingItem>(); // headers.addAll(workbench.getWorkbenchTemplate().getWorkbenchTemplateMappingItems()); // Collections.sort(headers); // for (WorkbenchTemplateMappingItem mi : headers) // { // //using the workbench data model table. Not the actual specify table the column is mapped to. // //This MIGHT be less confusing // //System.out.println("setting header renderer for " + mi.getTableName() + "." + mi.getFieldName()); // spreadSheet.getColumnModel().getColumn(c++).setHeaderRenderer(new WbTableHeaderRenderer(mi.getTableName())); // } // // // NOTE: This needs to be done after the creation of the saveBtn. And after the creation of the header renderes. // initColumnSizes(spreadSheet, saveBtn); // See if we need to make the Image Frame visible // Commenting this out for now because it is so annoying. if (showImageView || hasOneOrMoreImages) { SwingUtilities.invokeLater(new Runnable() { public void run() { toggleImageFrameVisible(); SwingUtilities.invokeLater(new Runnable() { public void run() { final Frame f = (Frame) UIRegistry.get(UIRegistry.FRAME); f.toFront(); f.requestFocus(); } }); } }); } ((WorkbenchTask) ContextMgr.getTaskByClass(WorkbenchTask.class)).opening(this); ((SGRTask) ContextMgr.getTaskByClass(SGRTask.class)).opening(this); }
From source file:edu.ku.brc.specify.utilapps.BuildSampleDatabase.java
/** * Creates a single disciplineType collection. * @param disciplineName the name of the Discipline to use * @param disciplineName the disciplineType name * @return the entire list of DB object to be persisted *///from www.java 2 s . co m @SuppressWarnings("unchecked") public Collection createFishCollection(final Discipline discipline, final SpecifyUser user, final Agent userAgent, final Division division, final Journal journal, final List<Object> taxa, final List<Object> geos, final String colPrefix, final String colName, final boolean isVoucherCol, final boolean doTissues, final CollectionChoice choice) { createStep = 0; frame.setProcess(0, 15); frame.setDesc("Creating Collection " + colName); startTx(); Pair<AutoNumberingScheme, AutoNumberingScheme> pairANS = createAutoNumberingSchemes(choice); AutoNumberingScheme cns = pairANS.first; AutoNumberingScheme accessionNS = pairANS.second; persist(cns); persist(accessionNS); commitTx(); startTx(); //////////////////////////////// // Create Collection //////////////////////////////// log.info("Creating a Collection"); Collection collection = createCollection(colPrefix, colName, choice.getCatalogNumberingFmtName(), cns, discipline, false); persist(collection); AppContextMgr.getInstance().setClassObject(Collection.class, collection); division.addReference(accessionNS, "numberingSchemes"); persist(division); //////////////////////////////// // Default user groups and test user //////////////////////////////// Map<String, SpPrincipal> groupMap = DataBuilder.createStandardGroups(session, collection); // add the administrator as a Collections Manager in this group user.addUserToSpPrincipalGroup(groupMap.get(SpecifyUserTypes.UserType.Manager.toString())); persist(user); // Tester String userPrefix = (isVoucherCol) ? "" : "Tis"; createAndAddTesterToCollection(session, userPrefix + "FishTester", "fishtester@brc.ku.edu", userPrefix + "FishTester", "", "Fish", "", "Tester", "", discipline, division, collection, groupMap, "Guest"); commitTx(); //////////////////////////////// // picklists //////////////////////////////// log.info("Creating picklists"); createPickLists(session, null); BldrPickList colMethods = createPickLists(session, discipline); frame.setProcess(++createStep); startTx(); //DBTableIdMgr schema = new DBTableIdMgr(false); //schema.initialize(new File(XMLHelper.getConfigDirPath("specify_datamodel.xml"))); //loadSchemaLocalization(discipline, SpLocaleContainer, schema); //buildDarwinCoreSchema(discipline); AppContextMgr.getInstance().setClassObject(SpecifyUser.class, user); user.addReference(userAgent, "agents"); persist(user); frame.setProcess(++createStep); Vector<Object> dataObjects = new Vector<Object>(); standardQueries(dataObjects, userAgent); persist(dataObjects); dataObjects.clear(); //startTx(); persist(dataObjects); //commitTx(); dataObjects.clear(); frame.setProcess(++createStep); //////////////////////////////// // localities //////////////////////////////// List<Locality> localities = new Vector<Locality>(); String POINT = "Point"; String LINE = "Line"; String RECT = "Rectangle"; Locality forestStream; Locality lake; Locality clintonLake; Locality farmpond; if (isVoucherCol) { log.info("Creating localities"); forestStream = createLocality("Unnamed forest stream pond", (Geography) geos.get(12)); localities.add(forestStream); globalLocalities.add(forestStream); forestStream.setLatLongType(POINT); forestStream.setOriginalLatLongUnit(0); forestStream.setLat1text("38.925467 deg N"); forestStream.setLatitude1(new BigDecimal(38.925467)); forestStream.setLong1text("94.984867 deg W"); forestStream.setLongitude1(new BigDecimal(-94.984867)); lake = createLocality("Deep, dark lake pond", (Geography) geos.get(17)); localities.add(lake); globalLocalities.add(lake); lake.setLatLongType(RECT); lake.setOriginalLatLongUnit(1); lake.setLat1text("41.548842 deg N"); lake.setLatitude1(new BigDecimal(41.548842)); lake.setLong1text("93.732129 deg W"); lake.setLongitude1(new BigDecimal(-93.732129)); lake.setLat2text("41.642195 deg N"); lake.setLatitude2(new BigDecimal(41.642195)); lake.setLong2text("100.403180 deg W"); lake.setLongitude2(new BigDecimal(-100.403180)); Geography douglasKS = null; for (Object o : geos) { if (o instanceof Geography) { Geography g = (Geography) o; if (g.getFullName().indexOf("Douglas") == 0) { douglasKS = g; } } } clintonLake = createLocality("Clinton Lake", douglasKS); localities.add(clintonLake); globalLocalities.add(clintonLake); farmpond = createLocality("Shoal Creek at Schermerhorn Park, S of Galena at Rt. 26", (Geography) geos.get(11)); localities.add(farmpond); globalLocalities.add(farmpond); farmpond.setLatLongType(LINE); farmpond.setOriginalLatLongUnit(2); farmpond.setLat1text("41.642187 deg N"); farmpond.setLatitude1(new BigDecimal(41.642187)); farmpond.setLong1text("100.403163 deg W"); farmpond.setLongitude1(new BigDecimal(-100.403163)); farmpond.setLat2text("49.647435 deg N"); farmpond.setLatitude2(new BigDecimal(49.647435)); farmpond.setLong2text("-55.112163 deg W"); farmpond.setLongitude2(new BigDecimal(-55.112163)); persist(forestStream); persist(lake); persist(farmpond); persist(clintonLake); } else { forestStream = globalLocalities.get(0); lake = globalLocalities.get(1); farmpond = globalLocalities.get(2); localities.addAll(globalLocalities); } frame.setProcess(++createStep); //////////////////////////////// // agents and addresses //////////////////////////////// log.info("Creating agents and addresses"); List<Agent> agents = new Vector<Agent>(); Agent johnByrn = null; Agent ku = new Agent(); if (isVoucherCol) { johnByrn = createAgent("mr", "John", "D", "Byrn", "jb", "jb@net.edu"); agents.add(createAgent("mr", "David", "D", "Smith", "ds", "ds@whitehouse.gov")); agents.add(createAgent("mr", "Robert", "H", "Burk", "rb", "beach@net.edu")); agents.add(createAgent("mrs", "Margaret", "H", "Johnson", "jm", "jm@net.edu")); agents.add(createAgent("mr", "Kip", "C", "Spencer", "kcs", "kip@ku.edu")); agents.add(johnByrn); agents.add(createAgent("sir", "Dudley", "X", "Thompson", "dxt", "")); agents.add(createAgent("mr", "Joe", "A", "Campbell", "jb", "")); agents.add(createAgent("mr", "Joe", "A", "Tester", "jb", "")); agents.add(createAgent("mr", "Mitch", "A", "Smyth", "mas", "mas@ku.edu")); agents.add(userAgent); ku.initialize(); ku.setAbbreviation("KU"); ku.setAgentType(Agent.ORG); ku.setLastName("University of Kansas"); ku.setEmail("webadmin@ku.edu"); ku.setTimestampCreated(new Timestamp(System.currentTimeMillis())); ku.setDivision(AppContextMgr.getInstance().getClassObject(Division.class)); agents.add(ku); agents.get(0).setOrganization(ku); agents.get(1).setOrganization(ku); agents.get(2).setOrganization(ku); agents.get(3).setOrganization(ku); agents.get(8).setOrganization(ku); Agent otherAgent = new Agent(); otherAgent.initialize(); otherAgent.setAbbreviation("O"); otherAgent.setAgentType(Agent.OTHER); otherAgent.setLastName("The Other Guys"); otherAgent.setEmail("other@other.com"); otherAgent.setTimestampCreated(new Timestamp(System.currentTimeMillis())); otherAgent.setDivision(AppContextMgr.getInstance().getClassObject(Division.class)); agents.add(otherAgent); List<GroupPerson> gpList = new ArrayList<GroupPerson>(); if (true) { startTx(); Agent gm1 = createAgent("mr", "John", "A", "Lyon", "jal", "jal@group.edu"); Agent gm2 = createAgent("mr", "Dave", "D", "Jones", "ddj", "ddj@group.edu"); persist(gm1); persist(gm2); commitTx(); //Discipline dsp = AppContextMgr.getInstance().getClassObject(Discipline.class); Agent groupAgent = new Agent(); groupAgent.initialize(); groupAgent.setAbbreviation("GRP"); groupAgent.setAgentType(Agent.GROUP); groupAgent.setLastName("The Group"); groupAgent.setEmail("group@group.com"); groupAgent.setTimestampCreated(new Timestamp(System.currentTimeMillis())); groupAgent.setDivision(AppContextMgr.getInstance().getClassObject(Division.class)); agents.add(groupAgent); gpList.add(createGroupPerson(groupAgent, gm1, 0, division)); gpList.add(createGroupPerson(groupAgent, gm2, 1, division)); } globalAgents.addAll(agents); List<AgentVariant> agentVariants = new Vector<AgentVariant>(); agentVariants.add(createAgentVariant(AgentVariant.VARIANT, "John Variant #1", johnByrn)); agentVariants.add(createAgentVariant(AgentVariant.VERNACULAR, "John VERNACULAR #1", johnByrn)); List<Address> addrs = new Vector<Address>(); addrs.add(createAddress(agents.get(1), "1600 Pennsylvania Avenue NW", null, "Washington", "DC", "USA", "20500", 0)); addrs.add(createAddress(agents.get(1), "??? Mississippi", null, "Lawrence", "KS", "USA", "66045", 1)); addrs.add(createAddress(agents.get(2), "1 Main St", "", "Lenexa", "KS", "USA", "66071")); addrs.add(createAddress(agents.get(3), "13355 Inverness", "Bldg #3", "Lawrence", "KS", "USA", "66047")); addrs.add(createAddress(agents.get(4), "Natural History Museum", "Cromwell Rd", "London", null, "UK", "SW7 5BD")); addrs.add(createAddress(agents.get(6), "1212 Apple Street", null, "Chicago", "IL", "USA", "01010")); addrs.add(createAddress(agents.get(8), "11911 Oak Ln", null, "Orion", "KS", "USA", "66061")); addrs.add(createAddress(ku, null, null, "Lawrence", "KS", "USA", "66045")); addrs.add(createAddress(userAgent, "1214 East Street", null, "Grinnell", "IA", "USA", "56060")); persist(agents); persist(agentVariants); persist(gpList); } else { agents.addAll(globalAgents); johnByrn = agents.get(4); ku = agents.get(10); } frame.setProcess(++createStep); //////////////////////////////// // collecting events (collectors, collecting trip) //////////////////////////////// log.info("Creating collecting events, collectors and a collecting trip"); Collector collectorMitch = createCollector(agents.get(8), 2); Collector collectorJim = createCollector(agents.get(1), 1); calendar.set(1993, 3, 19, 11, 56, 00); String stationFieldNumber = String.format(STATION_FIELD_FORMAT, stationFieldNumberCounter++); CollectingEvent ce1 = createCollectingEvent(forestStream, calendar, stationFieldNumber, new Collector[] { collectorMitch, collectorJim }); ce1.setStartDateVerbatim("19 Mar 1993, 11:56 AM"); calendar.set(1993, 3, 19, 13, 03, 00); ce1.setEndDate(calendar); ce1.setEndDateVerbatim("19 Mar 1993, 1:03 PM"); ce1.setMethod(colMethods.getItem(1).getValue()); AttributeDef cevAttrDef = createAttributeDef(AttributeIFace.FieldType.StringType, "ParkName", discipline, null);//meg added cod //startTx(); persist(cevAttrDef); //commitTx(); CollectingEventAttr cevAttr = createCollectingEventAttr(ce1, cevAttrDef, "Sleepy Hollow", null); Collector collectorMeg = createCollector(agents.get(2), 1); Collector collectorRod = createCollector(agents.get(3), 2); calendar.set(1993, 3, 20, 06, 12, 00); stationFieldNumber = String.format(STATION_FIELD_FORMAT, stationFieldNumberCounter++); CollectingEvent ce2 = createCollectingEvent(farmpond, calendar, stationFieldNumber, new Collector[] { collectorMeg, collectorRod }); ce2.setStartDateVerbatim("20 Mar 1993, 6:12 AM"); calendar.set(1993, 3, 20, 07, 31, 00); ce2.setEndDate(calendar); ce2.setEndDateVerbatim("20 Mar 1993, 7:31 AM"); ce2.setMethod(colMethods.getItem(2).getValue()); CollectingTrip trip = createCollectingTrip("My Collecint Trip", "Sample collecting trip", new CollectingEvent[] { ce1, ce2 }); int[] mn = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; Vector<CollectingEvent> ceList = new Vector<CollectingEvent>(); boolean oldWay = false; if (!oldWay) { int monInx = rand.nextInt(12); int dayInx = rand.nextInt(mn[monInx]); calendar.set(1990 + rand.nextInt(15), monInx + 1, dayInx + 1, rand.nextInt(24), rand.nextInt(60), rand.nextInt(60)); stationFieldNumber = String.format(STATION_FIELD_FORMAT, stationFieldNumberCounter++); Collector collector = null; int coltrInx = rand.nextInt(4); switch (coltrInx) { case 0: collector = collectorMitch; break; case 1: collector = collectorJim; break; case 2: collector = collectorMeg; break; case 3: collector = collectorRod; break; default: collector = collectorRod; break; } Locality loc = globalLocalities.get(rand.nextInt(globalLocalities.size())); CollectingEvent ce = createCollectingEvent(loc, calendar, stationFieldNumber, new Collector[] { collector }); //ce1.setStartDateVerbatim("19 Mar 1993, 11:56 AM"); ceList.add(ce); dataObjects.add(ce); } dataObjects.add(trip); dataObjects.add(ce1); dataObjects.add(cevAttr); dataObjects.add(ce2); dataObjects.add(collectorMitch); dataObjects.add(collectorJim); dataObjects.add(collectorMeg); dataObjects.add(collectorRod); //startTx(); persist(dataObjects); //commitTx(); dataObjects.clear(); //////////////////////////////// // permit //////////////////////////////// log.info("Creating a permit"); Calendar issuedDate = Calendar.getInstance(); issuedDate.set(1993, 1, 12); Calendar startDate = Calendar.getInstance(); startDate.set(1993, 2, 1); Calendar endDate = Calendar.getInstance(); endDate.set(1993, 5, 30); Permit permit = createPermit("1993-FISH-0001", "US Dept Wildlife", issuedDate, startDate, endDate, null); permit.setIssuedTo(ku); permit.setIssuedBy(agents.get(4)); dataObjects.add(permit); log.info("Creating a repository agreement"); RepositoryAgreement repoAg = new RepositoryAgreement(); repoAg.initialize(); repoAg.setDivision(division); repoAg.setRepositoryAgreementNumber("KU-1992-01"); repoAg.setOriginator(ku); Calendar received = Calendar.getInstance(); received.set(1992, 2, 10); repoAg.setDateReceived(received); Calendar repoEndDate = Calendar.getInstance(); received.set(2010, 2, 9); repoAg.setEndDate(repoEndDate); dataObjects.add(repoAg); //startTx(); persist(dataObjects); //commitTx(); dataObjects.clear(); frame.setProcess(++createStep); //////////////////////////////// // collection objects //////////////////////////////// log.info("Creating collection objects"); List<DNASequence> dnaObjs = new Vector<DNASequence>(); List<CollectionObject> collObjs = new Vector<CollectionObject>(); Collection col = collection; Calendar[] catDates = new Calendar[oldWay ? 8 : 50]; for (int i = 0; i < catDates.length; i++) { catDates[i] = Calendar.getInstance(); catDates[i].set(catDates[i].get(Calendar.YEAR), 01, 12 + i); } String prefix = "000000"; if (oldWay) { collObjs.add(createCollectionObject(prefix + "100", "RSC100", agents.get(0), col, 3, ce1, catDates[0], "BuildSampleDatabase")); collObjs.add(createCollectionObject(prefix + "101", "RSC101", agents.get(0), col, 2, ce1, catDates[1], "BuildSampleDatabase")); collObjs.add(createCollectionObject(prefix + "102", "RSC102", agents.get(1), col, 7, ce1, catDates[2], "BuildSampleDatabase")); collObjs.add(createCollectionObject(prefix + "103", "RSC103", agents.get(1), col, 12, ce1, catDates[3], "BuildSampleDatabase")); collObjs.add(createCollectionObject(prefix + "104", "RSC104", agents.get(2), col, 8, ce2, catDates[4], "BuildSampleDatabase")); collObjs.add(createCollectionObject(prefix + "105", "RSC105", agents.get(2), col, 1, ce2, catDates[5], "BuildSampleDatabase")); collObjs.add(createCollectionObject(prefix + "106", "RSC106", agents.get(2), col, 1, ce2, catDates[6], "BuildSampleDatabase")); collObjs.add(createCollectionObject(prefix + "107", "RSC107", agents.get(3), col, 1, ce2, catDates[7], "BuildSampleDatabase")); } else { for (int i = 0; i < catDates.length; i++) { Integer catNum = i + 100; int agentInx = rand.nextInt(agents.size()); CollectingEvent ce = ceList.get(rand.nextInt(ceList.size())); collObjs.add(createCollectionObject(prefix + catNum, "RSC" + catNum, agents.get(agentInx), col, rand.nextInt(12) + 1, ce, catDates[i], "BuildSampleDatabase")); } /* Comp. A : 148 Comp. G : 131 Comp. C : 199 Comp. T : 174 Ambiguous : 0 123456789012345678901234567890123456789012345678901234567890123456789012345 CCTGTATTTAGTATTTGGTGCCTGAGCAGGCATAGTCGGCACAGCCCTCAGCCTTCTGATCCGTGCCGAACTGAG CCAACCCGGTGCCCTGCTTGGCGATGATCAGATCTACAATGTTATCGTCACAGCCCACGCCTTTGTCATGATTTT CTTTATAGTAATACCCATCATAATTGGCGGATTCGGAAACTGACTGGTCCCCCTAATAATTGGGGCCCCAGACAT GGCATTTCCTCGCATGAACAATATGAGCTTCTGACTCCTACCCCCATCCTTCCTACTCCTTTTAGCCTCCTCTGG GGTAGAGGCCGGAGCCGGCACAGGGTGAACTGTTTACCCCCCACTGGCGGGAAACCTGGCCCATGCAGGAGCCTC TGTAGACCTAACCATTTTCTCCCTTCACCTGGCTGGGGTTTCGTCCATTTTGGGGGCTATTAATTTTATTACCAC CATTATTAACATGAAACCCCCCGCAGTATCCCAATATCAGACACCTCTATTTGTGTGATCTGTATTAATCACGGC CGTACTTCTCCTACTATCACTGCCAGTGCTAGCTGCAGGGATCACAATGCTCCTAACAGACCGAAATTTAAACAC CACCTTCTTTGACCCAGCCGGAGGAGGAGACCCCATCCTCTACCAACACCTA */ char[] syms = { 'A', 'C', 'T', 'G', }; for (int i = 0; i < catDates.length; i++) { int monInx = rand.nextInt(12); int dayInx = rand.nextInt(mn[monInx]); Calendar cal = Calendar.getInstance(); cal.set(2006 + rand.nextInt(3), monInx + 1, dayInx + 1, rand.nextInt(24), rand.nextInt(60), rand.nextInt(60)); DNASequence dna = new DNASequence(); dna.initialize(); //dna.setSeqDate(cal); //moved to DNASequencingRun dna.setCollectionMemberId(collObjs.get(i).getCollectionMemberId()); dna.setCollectionObject(collObjs.get(i)); //dna.setGeneName("COI5'"); int agentInx = rand.nextInt(agents.size()); dna.setCreatedByAgent(agents.get(agentInx)); dna.setSequencer(agents.get(agentInx)); StringBuilder sb = new StringBuilder(); for (int j = 0; j < ((8 * 75) + 52); j++) { sb.append(syms[rand.nextInt(syms.length)]); } dna.setGeneSequence(sb.toString()); //dna.setPcrPrimerFwd("C_VF1LFt1"); //moved to DNASequencingRun (sort of) //dna.setPcrPrimerRev("C_VR1LRt1"); //moved to DNASequencingRun (sort of) //dna.setProcessIdentifier("M13R"); //moved to DNASequencingRun (sort of) if (rand.nextInt(3) < 2) { //dna.setBarCodeIdent(String.format("NOSMF%03d-%d02", rand.nextInt(1000), i)); //moved to DNASequencingRun (sort of) Calendar submDate = (Calendar) cal.clone(); submDate.add(Calendar.DAY_OF_MONTH, 12); //dna.setSubmissionDate(submDate); } dnaObjs.add(dna); } } AttributeDef colObjAttrDef = createAttributeDef(AttributeIFace.FieldType.StringType, "MoonPhase", discipline, null);//meg added cod colObjAttrDef.setDiscipline(discipline); discipline.getAttributeDefs().add(colObjAttrDef); CollectionObjectAttr colObjAttr = createCollectionObjectAttr(collObjs.get(0), colObjAttrDef, "Full", null); dataObjects.add(colObjAttrDef); dataObjects.addAll(collObjs); dataObjects.addAll(dnaObjs); dataObjects.add(colObjAttr); //startTx(); persist(dataObjects); //commitTx(); dataObjects.clear(); frame.setProcess(++createStep); //////////////////////////////// // determinations (determination status) //////////////////////////////// log.info("Creating determinations"); List<Determination> determs = new Vector<Determination>(); Calendar recent = Calendar.getInstance(); recent.set(2006, 10, 27, 13, 44, 00); Calendar longAgo = Calendar.getInstance(); longAgo.set(1976, 01, 29, 8, 12, 00); Calendar whileBack = Calendar.getInstance(); whileBack.set(2002, 7, 4, 9, 33, 12); int baseInx = 41 - (doShallowTaxonTree ? 30 : 0); if (oldWay) { determs.add(createDetermination(collObjs.get(0), agents.get(0), (Taxon) taxa.get(baseInx + 1), true, recent)); determs.add(createDetermination(collObjs.get(1), agents.get(0), (Taxon) taxa.get(baseInx + 2), true, recent)); determs.add(createDetermination(collObjs.get(2), agents.get(0), (Taxon) taxa.get(baseInx + 3), true, recent)); determs.add(createDetermination(collObjs.get(3), agents.get(0), (Taxon) taxa.get(baseInx + 4), true, recent)); determs.add(createDetermination(collObjs.get(4), agents.get(0), (Taxon) taxa.get(baseInx + 5), true, recent)); determs.add(createDetermination(collObjs.get(5), agents.get(0), (Taxon) taxa.get(baseInx + 6), true, recent)); determs.add(createDetermination(collObjs.get(6), agents.get(3), (Taxon) taxa.get(baseInx + 7), true, recent)); determs.add(createDetermination(collObjs.get(7), agents.get(4), (Taxon) taxa.get(baseInx + 8), true, recent)); determs.add( createDetermination(collObjs.get(0), agents.get(0), (Taxon) taxa.get(baseInx), false, longAgo)); determs.add(createDetermination(collObjs.get(1), agents.get(1), (Taxon) taxa.get(baseInx + 7), false, whileBack)); determs.add(createDetermination(collObjs.get(2), agents.get(1), (Taxon) taxa.get(baseInx + 9), false, whileBack)); determs.add(createDetermination(collObjs.get(3), agents.get(2), (Taxon) taxa.get(baseInx + 10), false, whileBack)); determs.add(createDetermination(collObjs.get(4), agents.get(2), (Taxon) taxa.get(baseInx + 10), false, whileBack)); determs.add(createDetermination(collObjs.get(4), agents.get(3), (Taxon) taxa.get(baseInx + 13), false, longAgo)); determs.add(createDetermination(collObjs.get(4), agents.get(4), (Taxon) taxa.get(baseInx + 12), false, longAgo)); determs.get(13).setRemarks("This determination is totally wrong. What a foolish determination."); } else { for (CollectionObject co : collObjs) { determs.add(createDetermination(co, agents.get(0), (Taxon) taxa.get(baseInx + rand.nextInt(13)), true, recent)); } } //startTx(); persist(determs); //commitTx(); dataObjects.clear(); frame.setProcess(++createStep); //////////////////////////////// // preparations (prep types) //////////////////////////////// log.info("Creating preparations"); Vector<PrepType> prepTypesForSaving = loadPrepTypes(discipline.getType()); Vector<PrepType> pt = new Vector<PrepType>(); if (doTissues) { pt.clear(); PrepType tissuePT = createPrepType(collection, "Tissue"); for (int i = 0; i < prepTypesForSaving.size(); i++) { pt.add(tissuePT); } prepTypesForSaving.clear(); prepTypesForSaving.add(tissuePT); } else { pt.addAll(prepTypesForSaving); } List<Preparation> preps = new Vector<Preparation>(); Calendar prepDate = Calendar.getInstance(); if (oldWay) { preps.add(createPreparation(pt.get(0), agents.get(0), collObjs.get(0), (Storage) locs.get(7), rand.nextInt(20) + 1, prepDate)); preps.add(createPreparation(pt.get(0), agents.get(0), collObjs.get(1), (Storage) locs.get(7), rand.nextInt(20) + 1, prepDate)); preps.add(createPreparation(pt.get(0), agents.get(1), collObjs.get(2), (Storage) locs.get(7), rand.nextInt(20) + 1, prepDate)); preps.add(createPreparation(pt.get(0), agents.get(1), collObjs.get(3), (Storage) locs.get(7), rand.nextInt(20) + 1, prepDate)); preps.add(createPreparation(pt.get(0), agents.get(2), collObjs.get(4), (Storage) locs.get(8), rand.nextInt(20) + 1, prepDate)); preps.add(createPreparation(pt.get(0), agents.get(2), collObjs.get(5), (Storage) locs.get(8), rand.nextInt(20) + 1, prepDate)); preps.add(createPreparation(pt.get(0), agents.get(3), collObjs.get(6), (Storage) locs.get(8), rand.nextInt(20) + 1, prepDate)); preps.add(createPreparation(pt.get(0), agents.get(3), collObjs.get(7), (Storage) locs.get(8), rand.nextInt(20) + 1, prepDate)); preps.add(createPreparation(pt.get(1), agents.get(1), collObjs.get(0), (Storage) locs.get(11), rand.nextInt(20) + 1, prepDate)); preps.add(createPreparation(pt.get(1), agents.get(1), collObjs.get(1), (Storage) locs.get(11), rand.nextInt(20) + 1, prepDate)); preps.add(createPreparation(pt.get(1), agents.get(1), collObjs.get(2), (Storage) locs.get(10), rand.nextInt(20) + 1, prepDate)); preps.add(createPreparation(pt.get(1), agents.get(2), collObjs.get(3), (Storage) locs.get(9), rand.nextInt(20) + 1, prepDate)); preps.add(createPreparation(pt.get(1), agents.get(3), collObjs.get(4), (Storage) locs.get(9), rand.nextInt(20) + 1, prepDate)); preps.add(createPreparation(pt.get(1), agents.get(0), collObjs.get(5), (Storage) locs.get(9), rand.nextInt(20) + 1, prepDate)); preps.add(createPreparation(pt.get(2), agents.get(1), collObjs.get(6), (Storage) locs.get(9), rand.nextInt(20) + 1, prepDate)); preps.add(createPreparation(pt.get(2), agents.get(1), collObjs.get(7), (Storage) locs.get(9), rand.nextInt(20) + 1, prepDate)); preps.add(createPreparation(pt.get(2), agents.get(1), collObjs.get(2), (Storage) locs.get(8), rand.nextInt(20) + 1, prepDate)); preps.add(createPreparation(pt.get(3), agents.get(1), collObjs.get(0), (Storage) locs.get(7), rand.nextInt(20) + 1, prepDate)); preps.add(createPreparation(pt.get(3), agents.get(1), collObjs.get(1), (Storage) locs.get(7), rand.nextInt(20) + 1, prepDate)); preps.add(createPreparation(pt.get(3), agents.get(1), collObjs.get(2), (Storage) locs.get(8), rand.nextInt(20) + 1, prepDate)); preps.add(createPreparation(pt.get(3), agents.get(1), collObjs.get(3), (Storage) locs.get(8), rand.nextInt(20) + 1, prepDate)); preps.add(createPreparation(pt.get(3), agents.get(1), collObjs.get(4), (Storage) locs.get(9), rand.nextInt(20) + 1, prepDate)); } else { for (CollectionObject co : collObjs) { preps.add(createPreparation(pt.get(0), agents.get(rand.nextInt(4)), co, (Storage) locs.get(rand.nextInt(6) + 7), rand.nextInt(20) + 1, prepDate)); } } dataObjects.add(collection); dataObjects.addAll(prepTypesForSaving); dataObjects.addAll(preps); //startTx(); persist(dataObjects); //commitTx(); dataObjects.clear(); frame.setProcess(++createStep); //////////////////////////////// // accessions (accession agents) //////////////////////////////// log.info("Creating accessions and accession agents"); calendar.set(2006, 10, 27, 23, 59, 59); int yr = 2000 + (int) (rand.nextDouble() * 7); Accession acc1 = createAccession(division, "gift", "complete", yr + "-IC-001", DateFormat.getInstance().format(calendar.getTime()), calendar, calendar); acc1.setText1("Ichthyology"); acc1.setRepositoryAgreement(repoAg); Agent donor = agents.get(4); Agent receiver = agents.get(1); Agent reviewer = agents.get(2); List<AccessionAgent> accAgents = new Vector<AccessionAgent>(); accAgents.add(createAccessionAgent("donor", donor, acc1, null)); accAgents.add(createAccessionAgent("receiver", receiver, acc1, null)); accAgents.add(createAccessionAgent("reviewer", reviewer, acc1, null)); Accession acc2 = createAccession(division, "field_work", "inprocess", yr + "-IC-002", DateFormat.getInstance().format(calendar.getTime()), calendar, calendar); Agent donor2 = agents.get(5); Agent receiver2 = agents.get(3); Agent reviewer2 = agents.get(1); accAgents.add(createAccessionAgent("donor", donor2, acc2, null)); accAgents.add(createAccessionAgent("receiver", receiver2, acc2, null)); accAgents.add(createAccessionAgent("reviewer", reviewer2, acc2, null)); dataObjects.add(acc1); dataObjects.add(acc2); dataObjects.addAll(accAgents); //startTx(); persist(dataObjects); //commitTx(); dataObjects.clear(); frame.setProcess(++createStep); createLoanExamples(preps, agents, dataObjects); frame.setProcess(++createStep); //startTx(); persist(dataObjects); //commitTx(); dataObjects.clear(); /*if (false) { TaxonCitation taxonCitation = new TaxonCitation(); taxonCitation.initialize(); Taxon taxon11 = (Taxon)taxa.get(11); taxonCitation.setTaxon(taxon11); taxonCitation.setReferenceWork(rwList.get(0)); rwList.get(0).addTaxonCitations(taxonCitation); taxon11.getTaxonCitations().add(taxonCitation); dataObjects.add(taxonCitation); LocalityCitation localityCitation = new LocalityCitation(); localityCitation.initialize(); localityCitation.setLocality(ce1.getLocality()); ce1.getLocality().getLocalityCitations().add(localityCitation); localityCitation.setReferenceWork(rwList.get(1)); rwList.get(1).addLocalityCitations(localityCitation); dataObjects.add(localityCitation); }*/ //////////////////////////////// // Workbench //////////////////////////////// // setup a template and its mapping items String name = discipline.getName() + " DataSet"; WorkbenchTemplate wbTemplate = createWorkbenchTemplate(user, name, "These are the remarks"); WorkbenchTemplateMappingItem wbtmi0 = createWorkbenchMappingItem("CollectionObject", 1, "fieldNumber", "Field Number", 25, 0, 0, wbTemplate); WorkbenchTemplateMappingItem wbtmi1 = createWorkbenchMappingItem("CollectionObject", 1, "catalogedDate", "Cataloged Date", 25, 1, 1, wbTemplate); WorkbenchTemplateMappingItem wbtmi2 = createWorkbenchMappingItem("CollectionObject", 1, "catalogNumber", "Catalog Number", 25, 2, 2, wbTemplate); WorkbenchTemplateMappingItem wbtmi3 = createWorkbenchMappingItem("CollectionObject", 1, "collectionObjectYesNo1", "Yes/No", 8, 3, 3, wbTemplate); dataObjects.add(wbTemplate); dataObjects.add(wbtmi0); dataObjects.add(wbtmi1); dataObjects.add(wbtmi2); dataObjects.add(wbtmi3); // setup a workbench based on that template Workbench workBench = createWorkbench(user, name, "These are the remarks", "field_notebook.cvs", wbTemplate); dataObjects.add(workBench); // create a bunch of rows for the workbench for (int i = 1; i <= 14; ++i) { WorkbenchRow wbRow = workBench.addRow(); WorkbenchDataItem wbdi0 = createWorkbenchDataItem(wbRow, "RS-10" + i, 0); // just to make the dates look a little random int date = (i * 547) % 31 + 1; String dateStr = "0" + Integer.toString(date); dateStr = dateStr.substring(dateStr.length() - 2); WorkbenchDataItem wbdi1 = createWorkbenchDataItem(wbRow, "03/" + dateStr + "/2007", 1); WorkbenchDataItem wbdi2 = createWorkbenchDataItem(wbRow, "CN-10" + i, 2); String boolValAsStr = null; switch (i % 3) { case 0: { boolValAsStr = "true"; break; } case 1: { boolValAsStr = "false"; break; } case 2: { boolValAsStr = ""; break; } } boolValAsStr = ""; WorkbenchDataItem wbdi3 = createWorkbenchDataItem(wbRow, boolValAsStr, 3); WorkbenchRowImage wbRowImage = null; File f = new File(getDefaultWorkingPath() + File.separator + "demo_files" + File.separator + "card" + i + (i == 2 ? ".png" : ".jpg")); if (f.exists()) { try { int imageIndex = wbRow.addImage(f); if (imageIndex > -1) { wbRowImage = wbRow.getRowImage(imageIndex); } } catch (IOException e) { String msg = getResourceString("WB_IMG_ERR_LOAD"); getStatusBar().setErrorMessage(msg, e); log.error(msg, e); } } dataObjects.add(wbRow); dataObjects.add(wbdi0); dataObjects.add(wbdi1); dataObjects.add(wbdi2); if (wbRowImage != null) { dataObjects.add(wbRowImage); } // since some of these values will be "", the data item might be null if (wbdi3 != null) { dataObjects.add(wbdi3); } } // // create a workbench that uses the old, single-image capabilities // Workbench workBench2 = createWorkbench(user, name + " (pre-conversion)", "These are the remarks", "field_notebook.cvs", wbTemplate); // dataObjects.add(workBench2); // // // create a bunch of rows for the workbench // for (int i = 1; i <= 14; ++i) // { // WorkbenchRow wbRow = workBench2.addRow(); // WorkbenchDataItem wbdi0 = createWorkbenchDataItem(wbRow, "RS-10" + i, 0); // // // just to make the dates look a little random // int date = (i*547) % 31 + 1; // String dateStr = "0" + Integer.toString(date); // dateStr = dateStr.substring(dateStr.length()-2); // WorkbenchDataItem wbdi1 = createWorkbenchDataItem(wbRow, "03/" + dateStr + "/2007", 1); // WorkbenchDataItem wbdi2 = createWorkbenchDataItem(wbRow, "CN-10" + i, 2); // // String boolValAsStr = null; // switch (i % 3) // { // case 0: // { // boolValAsStr = "true"; // break; // } // case 1: // { // boolValAsStr = "false"; // break; // } // case 2: // { // boolValAsStr = ""; // break; // } // } // boolValAsStr = ""; // WorkbenchDataItem wbdi3 = createWorkbenchDataItem(wbRow, boolValAsStr, 3); // // WorkbenchRowImage wbRowImage = null; // // File f = new File("demo_files" + File.separator + "card" + i + (i == 2 ? ".png" : ".jpg")); // if (f.exists()) // { // try // { // // NOTE: this is not scaling the images to the proper sizes. Since this is just sample DB/test code, this isn't a problem. // byte[] imageData = FileUtils.readFileToByteArray(f); // wbRow.setCardImageData(imageData); // wbRow.setCardImageFullPath(f.getAbsolutePath()); // } // catch (IOException e) // { // log.error("Unable to add card image to workbench row", e); // } // } // // dataObjects.add(wbRow); // dataObjects.add(wbdi0); // dataObjects.add(wbdi1); // dataObjects.add(wbdi2); // if (wbRowImage != null) // { // dataObjects.add(wbRowImage); // } // // // since some of these values will be "", the data item might be null // if (wbdi3 != null) // { // dataObjects.add(wbdi3); // } // } startTx(); persist(dataObjects); commitTx(); dataObjects.clear(); frame.setProcess(++createStep); //////////////////////////////// // attachments (attachment metadata) //////////////////////////////// startTx(); log.info("Creating attachments and attachment metadata"); try { String attachmentFilesLoc = getDefaultWorkingPath() + File.separator + "demo_files" + File.separator; // String bigEyeFilePath = attachmentFilesLoc + "bigeye.jpg"; // Attachment bigEye = createAttachment(bigEyeFilePath, "image/jpeg", 0); // bigEye.setLoan(closedLoan); String[] names = { "Beach", "Smyth", "Spears", "Kumin", "Bentley" }; String[] photos = { "beach.jpg", "rod.jpg", "rod.jpg", "meg.jpg", "andy.jpg" }; for (Agent agent : agents) { for (int i = 0; i < names.length; i++) { if (agent.getLastName() != null && agent.getLastName().startsWith(names[i])) { String photoPath = attachmentFilesLoc + photos[i]; File file = new File(attachmentFilesLoc + photos[i]); if (!file.exists()) { continue; } // create the attachment record Attachment photoAttachment = createAttachment(photoPath, "image/jpeg", Agent.getClassTableId()); dataObjects.add(photoAttachment); // link the attachment to the agent AgentAttachment agentAttach = new AgentAttachment(); agentAttach.initialize(); agentAttach.setAgent(agent); agentAttach.setAttachment(photoAttachment); agentAttach.setOrderIndex(0); dataObjects.add(agentAttach); // add some metadata to the attachment record AttachmentMetadata copyrightData = new AttachmentMetadata(); copyrightData.initialize(); copyrightData.setName("Copyright"); copyrightData.setValue("2008"); photoAttachment.getMetadata().add(copyrightData); copyrightData.setAttachment(photoAttachment); dataObjects.add(copyrightData); AttachmentMetadata defPhotoIndicator = new AttachmentMetadata(); defPhotoIndicator.initialize(); defPhotoIndicator.setName("Default Photo"); defPhotoIndicator.setValue("yes"); photoAttachment.getMetadata().add(defPhotoIndicator); defPhotoIndicator.setAttachment(photoAttachment); dataObjects.add(defPhotoIndicator); // store the actual file into the attachment storage system AttachmentUtils.getAttachmentManager().setStorageLocationIntoAttachment(photoAttachment, true); photoAttachment.storeFile(false); // false means do not display an error dialog } } } // String giftPdfPath = attachmentFilesLoc + "2004-18.pdf"; // Attachment giftPDF = createAttachment(giftPdfPath, "application/pdf", 0); // giftPDF.setLoan(closedLoan); // // String accessionPdfPath = attachmentFilesLoc + "Seychelles.pdf"; // Attachment accPDF = createAttachment(accessionPdfPath, "application/pdf", 0); // // TODO: change this to setAccession() // accPDF.setPermit(permit); // // String sharkVideoPath = attachmentFilesLoc + "shark5.mpg"; // Attachment sharkVideo = createAttachment(sharkVideoPath, "video/mpeg4", 0); // sharkVideo.setLoan(closedLoan); // // Attachment sharkVideo2 = createAttachment(sharkVideoPath, "video/mpeg4", 0); // sharkVideo2.setCollectingEvent(ce1); // // String beakerPath = attachmentFilesLoc + "beaker.jpg"; // Attachment beakerAsBeach = createAttachment(beakerPath, "image/jpg", 1); // beakerAsBeach.setAgent(agents.get(1)); // // dataObjects.add(bigEye); // dataObjects.add(giftPDF); // dataObjects.add(accPDF); // dataObjects.add(sharkVideo); // dataObjects.add(sharkVideo2); // dataObjects.add(beakerAsBeach); } catch (Exception e) { log.error("Could not create attachments", e); } addConservatorData(agents, collObjs); commitTx(); frame.setProcess(++createStep); if (true) { List<Taxon> taxa2 = session.createQuery("SELECT t FROM Taxon t WHERE t.name = 'Ammocrypta'").list(); List<ReferenceWork> rwList = new Vector<ReferenceWork>(); startTx(); rwList.addAll(journal.getReferenceWorks()); TaxonCitation taxonCitation = new TaxonCitation(); taxonCitation.initialize(); Taxon ammocrypta = taxa2.get(0); taxonCitation.setTaxon(ammocrypta); taxonCitation.setReferenceWork(rwList.get(0)); rwList.get(0).addTaxonCitations(taxonCitation); ammocrypta.getTaxonCitations().add(taxonCitation); dataObjects.add(taxonCitation); persist(taxonCitation); if (isVoucherCol) { Locality locality = localities.get(0); LocalityCitation localityCitation = new LocalityCitation(); localityCitation.initialize(); localityCitation.setLocality(locality); locality.getLocalityCitations().add(localityCitation); localityCitation.setReferenceWork(rwList.get(1)); rwList.get(1).addLocalityCitations(localityCitation); dataObjects.add(localityCitation); persist(localityCitation); } commitTx(); } frame.setProcess(++createStep); //SpecifyDeleteHelper.showTableCounts("EmptyDB.txt", true); return collection; }