Example usage for javax.swing SwingUtilities getWindowAncestor

List of usage examples for javax.swing SwingUtilities getWindowAncestor

Introduction

In this page you can find the example usage for javax.swing SwingUtilities getWindowAncestor.

Prototype

public static Window getWindowAncestor(Component c) 

Source Link

Document

Returns the first Window ancestor of c, or null if c is not contained inside a Window.

Usage

From source file:org.omegat.gui.align.AlignPanelController.java

private void editRow(int row, int col) {
    String text = panel.table.getValueAt(row, col).toString();
    EditingPanelController splitter = new EditingPanelController(text);
    String newText = splitter.show(SwingUtilities.getWindowAncestor(panel.table));
    if (newText == null || text.equals(newText)) {
        return;/*from   w w  w . jav a  2 s  .c  om*/
    }
    modified = true;
    Rectangle initialRect = panel.table.getVisibleRect();
    panel.table.clearSelection();
    BeadTableModel model = (BeadTableModel) panel.table.getModel();
    model.editRow(row, col, newText);
    panel.table.changeSelection(row, col, false, false);
    ensureSelectionVisible(initialRect);
}

From source file:org.photovault.swingui.PhotoInfoDlg.java

/**
   Creates the UI components needed for this dialog.
*//*from   w w w .ja v  a 2  s .  c  o m*/
protected void createUI() {
    Container parentView = getParentController().getView();
    Window wnd = SwingUtilities.getWindowAncestor(parentView);
    dialogWindow = new JDialog((Frame) wnd);
    editor = new PhotoInfoEditor(this);
    addView(editor);
    dialogWindow.getContentPane().add(editor, BorderLayout.NORTH);
    final PhotoInfoDlg staticThis = this;

    registerAction("save_close", new DataAccessAction("OK") {
        public void actionPerformed(ActionEvent actionEvent, org.hibernate.Session currentSession) {
            save();
            dialogWindow.setVisible(false);
        }

    });
    registerAction("discard_close", new DataAccessAction("Cancel") {
        public void actionPerformed(ActionEvent actionEvent, org.hibernate.Session currentSession) {
            discard();
            dialogWindow.setVisible(false);
        }

    });

    JButton okBtn = new JButton(this.getActionAdapter("save_close"));
    //   okBtn.addActionListener( new ActionListener() {
    //            public void actionPerformed( ActionEvent e ) {
    //                try {
    //                    ChangePhotoInfoCommand cmd = ctrl.getChangeCommand();
    //                    masterCtrl.getCommandHandler().executeCommand( cmd );
    //                    photoChanged = true;
    //                    setVisible( false );
    //                } catch ( Exception ex ) {
    //                    JOptionPane.showMessageDialog(
    //                            staticThis,
    //                            "Error while saving changes: \n" + ex.getMessage(),
    //                            "Error saving changes",
    //                            JOptionPane.ERROR_MESSAGE,
    //                            null );
    //                    log.warn( "problem while saving changes: " + ex.getMessage() );
    //                }
    //            }
    //        } );

    JButton applyBtn = new JButton(getActionAdapter("save"));
    //        applyBtn.addActionListener( new ActionListener() {
    //            public void actionPerformed( ActionEvent e ) {
    //                try {
    //                    ChangePhotoInfoCommand cmd = ctrl.getChangeCommand();
    //                    masterCtrl.getCommandHandler().executeCommand( cmd );
    //                    photoChanged = true;
    //                } catch ( Exception ex ) {
    //                    JOptionPane.showMessageDialog(
    //                            staticThis,
    //                            "Error while saving changes: \n" + ex.getMessage(),
    //                            "Error saving changes",
    //                            JOptionPane.ERROR_MESSAGE,
    //                            null );
    //                    log.warn( "problem while saving changes: " + ex.getMessage() );
    //                }
    //            }
    //        } );

    JButton discardBtn = new JButton(getActionAdapter("discard"));
    //        discardBtn.addActionListener( new ActionListener() {
    //            public void actionPerformed( ActionEvent e ) {
    //                ctrl.discard();
    //            }
    //        } );

    JButton closeBtn = new JButton(getActionAdapter("discard_close"));
    //        closeBtn.addActionListener( new ActionListener() {
    //            public void actionPerformed( ActionEvent e ) {
    //                ctrl.discard();
    //                setVisible( false );
    //            }
    //        } );

    JPanel buttonPane = new JPanel();
    buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
    buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    buttonPane.add(Box.createHorizontalGlue());
    buttonPane.add(okBtn);
    buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
    buttonPane.add(applyBtn);
    buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
    buttonPane.add(discardBtn);
    buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
    buttonPane.add(closeBtn);
    dialogWindow.getContentPane().add(buttonPane, BorderLayout.SOUTH);

    dialogWindow.getRootPane().setDefaultButton(applyBtn);

    dialogWindow.pack();
}

From source file:org.qcc.modules.learningpalette.OptionsPlugin.LearningPalettePanel.java

private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed

    //First validate the input:
    //Palette Item name does not already exist, for one
    for (int i = 0; i < pItemCombo.getItemCount(); i++) {
        PaletteItem compare = (PaletteItem) pItemCombo.getItemAt(i);
        if (compare != selectedPaletteItem
                && compare.getItemName().trim().equals(this.itemNameText.getText().trim())) {
            JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(this),
                    "A palette item already exists with that name, choose a new name.");
            return;
        }//from  w  w  w . j  a va2 s.  c  o m
    }
    //That user has not started to type a customizer in and failed ot add it.
    //Custom button text
    if (customizerLabel.getText().trim().length() > 0 || customizerReplace.getText().trim().length() > 0) {
        Object[] options = { "Yes", "No" };
        int n = JOptionPane.showOptionDialog(SwingUtilities.getWindowAncestor(this),
                "You have started to add a customizer, but \n" + "have not clicked save, continue?",
                "Are you sure?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,
                options[1]);

        if (n != 0) {
            return;
        }
    }

    try {
        //Generate XML Document
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        org.w3c.dom.Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("PaletteItem");
        doc.appendChild(rootElement);

        Element category = doc.createElement("Category");
        category.setTextContent("User Defined");
        rootElement.appendChild(category);

        Element displayName = doc.createElement("DisplayName");
        displayName.setTextContent(this.itemNameText.getText().trim());
        rootElement.appendChild(displayName);

        Element toolTip = doc.createElement("Tooltip");
        toolTip.setTextContent(this.descriptionText.getText());
        rootElement.appendChild(toolTip);

        Element languagesParent = doc.createElement("Languages");

        for (String language : languageList) {
            String outputMapping;
            if (codeMapping.containsKey(language) == false) {
                outputMapping = "";
            } else {
                outputMapping = codeMapping.get(language);
            }

            Element languageParent = doc.createElement("Language");
            languageParent.setAttribute("id", language);
            Element codeTemplate = doc.createElement("codeTemplate");
            codeTemplate.setTextContent(outputMapping);
            languageParent.appendChild(codeTemplate);
            languagesParent.appendChild(languageParent);

        }
        rootElement.appendChild(languagesParent);

        //org.qcc.modules.learningpalette.LP_BasicInput.java
        Element paletteClass = doc.createElement("PaletteLogicClass");
        paletteClass.setTextContent("org.qcc.modules.learningpalette.LP_BasicInput");
        rootElement.appendChild(paletteClass);

        //Create Customizer (For later use)
        Element customizerParent = doc.createElement("Customizer");
        rootElement.appendChild(customizerParent);

        for (CustomizerControl control : customizerControls) {
            Element customizerItem = doc.createElement("Item");
            customizerItem.setAttribute("type", control.getType());
            customizerItem.setAttribute("name", control.getName());
            customizerItem.setAttribute("label", control.getLabel());
            customizerItem.setAttribute("value", "");
            customizerParent.appendChild(customizerItem);
        }

        //Create file name 
        if (currentFileName == null) {
            String fileName = "UserDefined_";

            //Random number
            int uniqueID = randInt(0, 9999999);
            //Random letter
            char c = (char) randInt(65, 90);

            currentFileName = fileName + uniqueID + c + ".xml";
        }

        //Get the directory to save to.
        String saveDirectory = System.getProperty("user.dir") + "\\LearningPaletteXML";

        //Make the directory if necessary
        File newDirectory = new File(saveDirectory);
        if (!newDirectory.exists()) {
            if (newDirectory.mkdir()) {
                System.out.println("Directory is created!");
            } else {
                System.out.println("Failed to create directory!");
            }
        }

        //Save the file
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        Result output = new StreamResult(new File(saveDirectory + "\\" + currentFileName));
        Source input = new DOMSource(doc);
        transformer.transform(input, output);

        loadPaletteItems((this.itemNameText.getText()));

        //Now reload the form with the saved list of palette items.
        //pItemCombo.revalidate();
        //pItemCombo.repaint();
    } catch (Exception ex) {
        //TODO: Exception handling.
        System.out.println(ex.getMessage());
    }

}

From source file:org.qcc.modules.learningpalette.OptionsPlugin.LearningPalettePanel.java

private void addCustomizerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addCustomizerActionPerformed
    //TODO: Validation

    String customizerTypeField = this.customizerType.getSelectedItem().toString();

    String replacementText = this.customizerReplace.getText().trim();
    String customizerLabel = this.customizerLabel.getText().trim();
    String defaultValue = "";

    if (replacementText.equals("")) {
        JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(this),
                "Replacement text cannot be empty. This text will be replaced in your code.");
        return;/*  w  w  w.  j a  v  a2s.com*/
    }

    if (customizerLabel.equals("")) {
        JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(this),
                "Label text cannot be empty. This text will be displayed on your popup customizer.");
        return;
    }

    //Verify no duplicates exist and no substrings exist
    for (int i = 0; i < customizerControls.size(); i++) {
        CustomizerControl item = customizerControls.get(i);
        if (item.getName().equals(replacementText)) {
            JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(this),
                    "This replacement customizer already exists, choose a new replacement text.");
            return;
        }

        if (replacementText.contains(item.getName()) || item.getName().contains(replacementText)) {
            JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(this),
                    "The replacement text for this customizer contains a substring of an existing item, or vice versa.\nThis can cause conflicts when a replacement is performed. Use more specific, unique customizer replacement texts.\n\nFor example, '$ABC' could conflict with '$ABCD', as a replace performed on $ABC would also replace [$ABC]D.");
            return;
        }
    }

    if (customizerTypeField.equals("Text")) {
        CustomizerTextField newTextField = new CustomizerTextField(this.customizerReplace.getText(),
                this.customizerLabel.getText(), "");
        customizerControls.add(newTextField);
    } else if (customizerTypeField.equals("Variable")) {
        CustomizerVariableField newVariableField = new CustomizerVariableField(this.customizerReplace.getText(),
                this.customizerLabel.getText(), "");
        customizerControls.add(newVariableField);
    } else if (customizerTypeField.equals("Expression")) {
        CustomizerExpressionField newExpressionField = new CustomizerExpressionField(
                this.customizerReplace.getText(), this.customizerLabel.getText(), "");
        customizerControls.add(newExpressionField);
    }

    this.customizerReplace.setText("");
    this.customizerLabel.setText("");

    updateCustomizers();

}

From source file:org.qcc.modules.learningpalette.OptionsPlugin.LearningPalettePanel.java

private void deleteSelectedItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteSelectedItemActionPerformed
    if (selectedPaletteItem != null) {
        Object[] options = { "Yes", "No" };
        int n = JOptionPane.showOptionDialog(SwingUtilities.getWindowAncestor(this),
                "This will delete the selected palette item permanently.\n"
                        + "Are you sure you wish to continue?",
                "Are you sure?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,
                options[1]);//from  www  .j a  v a  2s  .c o  m

        if (n != 0) {
            return;
        }

        //Step 1: Remove palette item from the combo box
        String fileName = selectedPaletteItem.getFileName();
        pItemCombo.removeItem(selectedPaletteItem);

        //Step 2: Delete the file if necessary
        if (fileName != null && fileName.equals("") == false) {
            String saveDirectory = System.getProperty("user.dir") + "\\LearningPaletteXML";

            //Make the directory if necessary
            File folder = new File(saveDirectory);
            if (!folder.exists()) {
                if (folder.mkdir()) {
                    System.out.println("Directory is created!");
                } else {
                    System.out.println("Failed to create directory!");
                }
            }

            File fileToDelete = null;
            File[] listOfFiles = folder.listFiles();
            for (File file : listOfFiles) {
                if (file.isFile()) {
                    if (file.getName().equals(fileName)) {
                        fileToDelete = file;
                    }
                }
            }

            if (fileToDelete != null) {
                fileToDelete.delete();
            }
        }

        //Step 3: call loadPaletteItems("")
        //Cleanup the form
        itemNameText.setText("");
        descriptionText.setText("");
        customizerReplace.setText("");
        customizerLabel.setText("");
        customizerList.removeAll();

        loadPaletteItems("");
    }
}

From source file:org.tellervo.desktop.bulkdataentry.command.ImportSelectedElementsCommand.java

/**
 * @see com.dmurph.mvc.control.ICommand#execute(com.dmurph.mvc.MVCEvent)
 *///from   ww  w. ja va  2  s  . c  o m
@Override
public void execute(MVCEvent argEvent) {
    BulkImportModel model = BulkImportModel.getInstance();
    ElementModel emodel = model.getElementModel();
    ElementTableModel tmodel = emodel.getTableModel();

    ArrayList<IBulkImportSingleRowModel> selected = new ArrayList<IBulkImportSingleRowModel>();
    tmodel.getSelected(selected);

    // here is where we verify they contain required info
    HashSet<String> requiredMessages = new HashSet<String>();
    ArrayList<IBulkImportSingleRowModel> incompleteModels = new ArrayList<IBulkImportSingleRowModel>();

    HashSet<String> definedProps = new HashSet<String>();
    for (IBulkImportSingleRowModel som : selected) {

        definedProps.clear();
        for (String s : SingleElementModel.TABLE_PROPERTIES) {
            if (som.getProperty(s) != null) {
                definedProps.add(s);
            }
        }
        boolean incomplete = false;

        // object 
        if (!definedProps.contains(SingleElementModel.OBJECT)) {
            requiredMessages.add("Cannot import without a parent object.");
            incomplete = true;
        } else if (fixTempObjectCode(som)) {
            // There was a temp code but it is fixed now
        } else {
            requiredMessages.add("Cannot import as parent object has not been created yet");
            incomplete = true;
        }

        // type
        if (!definedProps.contains(SingleElementModel.TYPE)) {
            requiredMessages.add("Element must contain a type.");
            incomplete = true;
        }

        // taxon
        if (!definedProps.contains(SingleElementModel.TAXON)) {
            requiredMessages.add("Element must contain a taxon.");
            incomplete = true;
        }

        // title
        if (!definedProps.contains(SingleElementModel.TITLE)) {
            requiredMessages.add("Element must have a title");
            incomplete = true;
        }

        // lat/long
        if (definedProps.contains(SingleElementModel.LATITUDE)
                || definedProps.contains(SingleElementModel.LONGITUDE)) {
            if (!definedProps.contains(SingleElementModel.LATITUDE)
                    || !definedProps.contains(SingleElementModel.LONGITUDE)) {
                requiredMessages
                        .add("If coordinates are specified then both latitude and longitude are required");
                incomplete = true;
            } else {
                String attempt = som.getProperty(SingleElementModel.LATITUDE).toString().trim();
                try {
                    Double lat = Double.parseDouble(attempt);
                    if (lat > -90 || lat < 90) {
                        requiredMessages.add("Latitude must be between -90 and 90");
                        incomplete = true;
                    }
                } catch (NumberFormatException e) {
                    requiredMessages.add("Cannot parse '" + attempt + "' into a number.");
                    incomplete = true;
                }
                attempt = som.getProperty(SingleElementModel.LONGITUDE).toString().trim();
                try {
                    Double lng = Double.parseDouble(attempt);
                    if (lng > -180 || lng < 180) {
                        requiredMessages.add("Longitude must be between -180 and 180");
                        incomplete = true;
                    }
                } catch (NumberFormatException e) {
                    requiredMessages.add("Cannot parse '" + attempt + "' into a number.");
                    incomplete = true;
                }
            }
        }

        if (definedProps.contains(SingleElementModel.HEIGHT) || definedProps.contains(SingleElementModel.WIDTH)
                || definedProps.contains(SingleElementModel.DEPTH)
                || definedProps.contains(SingleElementModel.DIAMETER)) {
            if (!definedProps.contains(SingleElementModel.UNIT)) {
                requiredMessages.add("Units must be specified when dimensions are included");
                incomplete = true;
            }

            if ((definedProps.contains(SingleElementModel.HEIGHT)
                    && definedProps.contains(SingleElementModel.DIAMETER)
                    && !definedProps.contains(SingleElementModel.WIDTH)
                    && !definedProps.contains(SingleElementModel.DEPTH))) {
                // h+diam but not width or depth
            } else if ((definedProps.contains(SingleElementModel.HEIGHT)
                    && definedProps.contains(SingleElementModel.WIDTH)
                    && definedProps.contains(SingleElementModel.DEPTH)
                    && !definedProps.contains(SingleElementModel.DIAMETER))) {
                // h+w+d but not diam
            } else {
                requiredMessages.add(
                        "When dimensions are included they must be: height/width/depth or height/diameter.");
                incomplete = true;
            }

        }

        if (incomplete) {
            incompleteModels.add(som);
        }
    }

    if (!incompleteModels.isEmpty()) {
        StringBuilder message = new StringBuilder();
        message.append("Please correct the following errors:\n");
        message.append(StringUtils.join(requiredMessages.toArray(), "\n"));
        Alert.message(model.getMainView(), "Importing Errors", message.toString());
        return;
    }

    // now we actually create the models
    int i = -1;
    boolean hideErrorMessage = false;
    for (IBulkImportSingleRowModel srm : selected) {
        i++;
        SingleElementModel som = (SingleElementModel) srm;
        TridasElement origElement = new TridasElement();

        if (!som.isDirty()) {
            System.out.println("Element isn't dirty, not saving/updating: "
                    + som.getProperty(SingleElementModel.TITLE).toString());
        }

        som.populateToTridasElement(origElement);

        Object o = som.getProperty(SingleElementModel.OBJECT);
        TridasObject parentObject = null;
        if (o instanceof TridasObjectOrPlaceholder) {
            parentObject = ((TridasObjectOrPlaceholder) o).getTridasObject();
        } else if (o instanceof TridasObject) {
            parentObject = (TridasObject) o;
        }

        EntityResource<TridasElement> resource;

        if (origElement.getIdentifier() != null) {
            resource = new EntityResource<TridasElement>(origElement, TellervoRequestType.UPDATE,
                    TridasElement.class);
        } else {
            resource = new EntityResource<TridasElement>(origElement, parentObject, TridasElement.class);
        }

        // set up a dialog...
        Window parentWindow = SwingUtilities.getWindowAncestor(model.getMainView());
        TellervoResourceAccessDialog dialog = new TellervoResourceAccessDialog(parentWindow, resource, i,
                selected.size());

        resource.query();
        dialog.setVisible(true);

        if (!dialog.isSuccessful()) {

            if (hideErrorMessage) {
                continue;
            } else if (i < selected.size() - 1) {
                // More records remain
                Object[] options = { "Yes", "Yes, but hide further messages", "No" };
                int result = JOptionPane.showOptionDialog(BulkImportModel.getInstance().getMainView(), //parent
                        I18n.getText("error.savingChanges") + ":" + System.lineSeparator() + // message
                                dialog.getFailException().getLocalizedMessage() + System.lineSeparator()
                                + System.lineSeparator()
                                + "Would you like to continue importing the remaining records?",
                        I18n.getText("error"), // title 
                        JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]);

                if (result == JOptionPane.NO_OPTION) {
                    hideErrorMessage = true;
                    continue;
                } else if (result == JOptionPane.YES_OPTION) {
                    continue;
                } else {
                    break;
                }
            } else {
                JOptionPane.showMessageDialog(BulkImportModel.getInstance().getMainView(), //parent
                        I18n.getText("error.savingChanges") + ":" + System.lineSeparator() + // message
                                dialog.getFailException().getLocalizedMessage(),
                        I18n.getText("error"), // title 
                        JOptionPane.ERROR_MESSAGE); //option

                break;
            }
        }
        som.populateFromTridasElement(resource.getAssociatedResult());
        som.setDirty(false);
        tmodel.setSelected(som, false);

        // add to imported list or update existing
        if (origElement.getIdentifier() != null) {
            TridasElement found = null;
            for (TridasElement tox : model.getElementModel().getImportedList()) {
                if (tox.getIdentifier().getValue().equals(origElement.getIdentifier().getValue())) {
                    found = tox;
                    break;
                }
            }
            if (found == null) {
                log.warn(
                        "Error updating model.  Couldn't find the object in the model to update so adding to imported list.");
                model.getElementModel().getImportedList().add(resource.getAssociatedResult());
            } else {
                resource.getAssociatedResult().copyTo(found);
            }
        } else {
            model.getElementModel().getImportedList().add(resource.getAssociatedResult());
        }

    }

    //      
    //      // finally, update the combo boxes in the table to the new options
    //      DynamicJComboBoxEvent event = new DynamicJComboBoxEvent(emodel.getImportedDynamicComboBoxKey(), emodel.getImportedListStrings());
    //      event.dispatch();

    tmodel.fireTableDataChanged();
}

From source file:org.tellervo.desktop.bulkdataentry.command.ImportSelectedObjectsCommand.java

/**
 * @see com.dmurph.mvc.control.ICommand#execute(com.dmurph.mvc.MVCEvent)
 *///from  w  w  w  .  j ava2  s  .co  m
@Override
public void execute(MVCEvent argEvent) {
    BulkImportModel model = BulkImportModel.getInstance();

    ObjectTableModel tmodel = model.getObjectModel().getTableModel();
    ArrayList<IBulkImportSingleRowModel> selected = new ArrayList<IBulkImportSingleRowModel>();
    tmodel.getSelected(selected);

    // here is where we verify they contain required info
    HashSet<String> requiredMessages = new HashSet<String>();
    ArrayList<IBulkImportSingleRowModel> incompleteModels = new ArrayList<IBulkImportSingleRowModel>();

    HashSet<String> definedProps = new HashSet<String>();
    HashSet<String> objectCodeSet = new HashSet<String>();
    for (IBulkImportSingleRowModel som : selected) {

        definedProps.clear();
        for (String s : SingleObjectModel.TABLE_PROPERTIES) {
            if (som.getProperty(s) != null) {
                definedProps.add(s);
            }
        }
        boolean incomplete = false;

        // object code
        if (!definedProps.contains(SingleObjectModel.OBJECT_CODE)) {
            requiredMessages.add("Cannot import without an object code.");
            incomplete = true;
        } else {
            String code = som.getProperty(SingleObjectModel.OBJECT_CODE).toString();
            if (code.length() < 3) {
                requiredMessages.add("Object code must be at least 3 characters");
                incomplete = true;
            }
            if (code.contains(" ")) {
                requiredMessages.add("Object code cannot contain whitespace.");
                incomplete = true;
            }
            if (objectCodeSet.contains(code)) {
                requiredMessages.add("There cannot be duplicate object codes.");
                incomplete = true;
            } else {
                objectCodeSet.add(code);
            }
        }

        if (definedProps.contains(SingleObjectModel.PARENT_OBJECT)) {
            if (this.fixTempObjectCode(som)) {
                // fixed
            } else {
                requiredMessages.add("Cannot import as parent object has not been created yet");
                incomplete = true;
            }
        }

        // type
        if (!definedProps.contains(SingleObjectModel.TYPE)) {
            requiredMessages.add("Object must contain type.");
            incomplete = true;
        }

        // title
        if (!definedProps.contains(SingleObjectModel.TITLE)) {
            requiredMessages.add("Object must have a title");
            incomplete = true;
        }

        // lat/long
        if (definedProps.contains(SingleObjectModel.LATITUDE)
                || definedProps.contains(SingleObjectModel.LONGITUDE)) {
            if (!definedProps.contains(SingleObjectModel.LATITUDE)
                    || !definedProps.contains(SingleObjectModel.LONGITUDE)) {
                requiredMessages
                        .add("If coordinates are specified then both latitude and longitude are required");
                incomplete = true;
            } else {
                String attempt = som.getProperty(SingleObjectModel.LATITUDE).toString().trim();
                try {
                    Double lat = Double.parseDouble(attempt);
                    if (lat > -90 || lat < 90) {
                        requiredMessages
                                .add("Latitude must be betweOne or more errors were encountereden -90 and 90");
                        incomplete = true;
                    }
                } catch (NumberFormatException e) {
                    requiredMessages.add("Cannot parse '" + attempt + "' into a number.");
                    incomplete = true;
                }
                attempt = som.getProperty(SingleObjectModel.LONGITUDE).toString().trim();
                try {
                    Double lng = Double.parseDouble(attempt);
                    if (lng > -180 || lng < 180) {
                        requiredMessages.add("Longitude must be between -180 and 180");
                        incomplete = true;
                    }
                } catch (NumberFormatException e) {
                    requiredMessages.add("Cannot parse '" + attempt + "' into a number.");
                    incomplete = true;
                }
            }
        }

        if (incomplete) {
            incompleteModels.add(som);
        }
    }

    if (!incompleteModels.isEmpty()) {
        StringBuilder message = new StringBuilder();
        message.append("Please correct the following errors:\n");
        message.append(StringUtils.join(requiredMessages.toArray(), "\n"));
        Alert.message(model.getMainView(), "Importing Errors", message.toString());
        return;
    }

    // now we actually create the models
    int i = 0;
    for (IBulkImportSingleRowModel srm : selected) {
        SingleObjectModel som = (SingleObjectModel) srm;
        TridasObjectEx origObject = new TridasObjectEx();

        if (!som.isDirty()) {
            System.out.println("Object isn't dirty, not saving/updating: "
                    + som.getProperty(SingleObjectModel.OBJECT_CODE).toString());
        }

        som.populateTridasObject(origObject);

        TridasObject parentObject = null;
        try {
            parentObject = ((TridasObjectOrPlaceholder) som.getProperty(SingleObjectModel.PARENT_OBJECT))
                    .getTridasObject();
        } catch (Exception e) {

        }

        EntityResource<TridasObjectEx> resource;
        if (origObject.getIdentifier() != null) {
            resource = new EntityResource<TridasObjectEx>(origObject, TellervoRequestType.UPDATE,
                    TridasObjectEx.class);
        } else {
            if (parentObject != null) {
                resource = new EntityResource<TridasObjectEx>(origObject, parentObject, TridasObjectEx.class);
            } else {
                resource = new EntityResource<TridasObjectEx>(origObject, TellervoRequestType.CREATE,
                        TridasObjectEx.class);
            }
        }

        // set up a dialog...
        Window parentWindow = SwingUtilities.getWindowAncestor(model.getMainView());
        TellervoResourceAccessDialog dialog = new TellervoResourceAccessDialog(parentWindow, resource, i,
                selected.size());

        resource.query();
        dialog.setVisible(true);

        if (!dialog.isSuccessful()) {
            JOptionPane.showMessageDialog(BulkImportModel.getInstance().getMainView(),
                    I18n.getText("error.savingChanges") + "\r\n" + I18n.getText("error") + ": "
                            + dialog.getFailException().getLocalizedMessage(),
                    I18n.getText("error"), JOptionPane.ERROR_MESSAGE);
            continue;
        }
        som.populateFromTridasObject(resource.getAssociatedResult());
        som.setDirty(false);
        tmodel.setSelected(som, false);

        // add to imported list or update existing
        if (origObject.getIdentifier() != null) {
            TridasObjectEx found = null;
            for (TridasObjectEx tox : model.getObjectModel().getImportedList()) {
                if (tox.getIdentifier().getValue().equals(origObject.getIdentifier().getValue())) {
                    found = tox;
                    break;
                }
            }
            if (found == null) {
                Alert.error("Error updating model",
                        "Couldn't find the object in the model to update, please report bug.");
            } else {
                resource.getAssociatedResult().copyTo(found);
                App.tridasObjects.updateTridasObject(found);
            }
        } else {
            model.getObjectModel().getImportedList().add(resource.getAssociatedResult());
            App.tridasObjects.addTridasObject(resource.getAssociatedResult());
        }

        i++;
    }

    // finally, update the combo boxes in the table to the new options
    //DynamicJComboBoxEvent event = new DynamicJComboBoxEvent(model.getObjectModel().getImportedDynamicComboBoxKey(), model.getObjectModel().getImportedListStrings());
    //event.dispatch();

    // FIXME this should be removed once other lists listen for changes in the object list
    //App.updateTridasObjectList();

}

From source file:org.tellervo.desktop.bulkdataentry.command.ImportSelectedSamplesCommand.java

/**
 * @see com.dmurph.mvc.control.ICommand#execute(com.dmurph.mvc.MVCEvent)
 *///from   w w w .j  av  a  2s .  c om
@Override
public void execute(MVCEvent argEvent) {
    BulkImportModel model = BulkImportModel.getInstance();
    SampleModel smodel = model.getSampleModel();
    SampleTableModel tmodel = smodel.getTableModel();

    ElementModel emodel = model.getElementModel();

    MVCArrayList<TridasElement> elementlist = emodel.getImportedList();
    ElementTableModel etablemodel = emodel.getTableModel();

    ArrayList<IBulkImportSingleRowModel> selected = new ArrayList<IBulkImportSingleRowModel>();
    tmodel.getSelected(selected);

    // here is where we verify they contain required info
    HashSet<String> requiredMessages = new HashSet<String>();
    ArrayList<SingleSampleModel> incompleteModels = new ArrayList<SingleSampleModel>();

    HashSet<String> definedProps = new HashSet<String>();
    for (IBulkImportSingleRowModel srm : selected) {
        SingleSampleModel som = (SingleSampleModel) srm;
        definedProps.clear();
        for (String s : SingleSampleModel.TABLE_PROPERTIES) {
            if (som.getProperty(s) != null) {
                definedProps.add(s);
            }
        }
        if (smodel.isRadiusWithSample()) {
            for (String s : SingleRadiusModel.PROPERTIES) {
                if (som.getRadiusModel().getProperty(s) != null) {
                    definedProps.add(s);
                }
            }
        }
        boolean incomplete = false;

        // object
        if (!definedProps.contains(SingleSampleModel.OBJECT)) {
            requiredMessages.add("Cannot import without a parent object.");
            incomplete = true;
        }

        // element 
        if (!definedProps.contains(SingleSampleModel.ELEMENT)) {
            requiredMessages.add("Cannot import without a parent element.");
            incomplete = true;
        } else if (fixTempParentCodes(som, emodel)) {
            // There was a temp code but it is fixed now
        } else {
            requiredMessages.add("Cannot import as parent element has not been created yet");
            incomplete = true;
        }

        // type
        if (!definedProps.contains(SingleSampleModel.TYPE)) {
            requiredMessages.add("Sample must contain a type.");
            incomplete = true;
        }

        // title
        if (!definedProps.contains(SingleSampleModel.TITLE)) {
            requiredMessages.add("Sample must have a title.");
            incomplete = true;
        }

        if (smodel.isRadiusWithSample()) {
            if (!definedProps.contains(SingleRadiusModel.TITLE)) {
                requiredMessages.add("Radius title must be populated.");
                incomplete = true;
            }
        }

        if (incomplete) {
            incompleteModels.add(som);
        }
    }

    if (!incompleteModels.isEmpty()) {
        StringBuilder message = new StringBuilder();
        message.append("Please correct the following errors:\n");
        message.append(StringUtils.join(requiredMessages.toArray(), "\n"));
        Alert.message(model.getMainView(), "Importing Errors", message.toString());
        return;
    }

    // now we actually create the models
    int i = 0;
    for (IBulkImportSingleRowModel srm : selected) {
        SingleSampleModel ssm = (SingleSampleModel) srm;
        TridasSample origSample = new TridasSample();

        if (!ssm.isDirty()) {
            System.out.println("Object isn't dirty, not saving/updating: "
                    + ssm.getProperty(SingleSampleModel.TITLE).toString());
        }

        ssm.populateToTridasSample(origSample);

        Object e = ssm.getProperty(SingleSampleModel.ELEMENT);
        TridasElement parentElement = null;
        if (e instanceof TridasElementOrPlaceholder) {
            parentElement = ((TridasElementOrPlaceholder) e).getTridasElement();
        } else if (e instanceof TridasElement) {
            parentElement = (TridasElement) e;
        }

        // sample first
        EntityResource<TridasSample> sampleResource;
        if (origSample.getIdentifier() != null) {
            sampleResource = new EntityResource<TridasSample>(origSample, TellervoRequestType.UPDATE,
                    TridasSample.class);
        } else {
            sampleResource = new EntityResource<TridasSample>(origSample, parentElement, TridasSample.class);
        }
        sampleResource.setProperty(TellervoResourceProperties.ENTITY_REQUEST_FORMAT,
                TellervoRequestFormat.SUMMARY);

        // set up a dialog...
        Window parentWindow = SwingUtilities.getWindowAncestor(model.getMainView());
        TellervoResourceAccessDialog dialog = new TellervoResourceAccessDialog(parentWindow, sampleResource, i,
                selected.size());

        sampleResource.query();
        dialog.setVisible(true);

        if (!dialog.isSuccessful()) {
            JOptionPane.showMessageDialog(BulkImportModel.getInstance().getMainView(),
                    I18n.getText("error.savingChanges") + "\r\n" + I18n.getText("error") + ": "
                            + dialog.getFailException().getLocalizedMessage(),
                    I18n.getText("error"), JOptionPane.ERROR_MESSAGE);
            continue;
        }
        ssm.populateFromTridasSample(sampleResource.getAssociatedResult());
        ssm.setDirty(false);
        tmodel.setSelected(ssm, false);

        // add to imported list or update existing
        if (origSample.getIdentifier() != null) {
            TridasSample found = null;
            for (TridasSample tox : model.getSampleModel().getImportedList()) {
                if (tox.getIdentifier().getValue().equals(origSample.getIdentifier().getValue())) {
                    found = tox;
                    break;
                }
            }
            if (found == null) {
                //Alert.error("Error updating model", "Couldn't find the object in the model to update, please report bug.");
            } else {
                sampleResource.getAssociatedResult().copyTo(found);
            }
        } else {
            model.getSampleModel().getImportedList().add(sampleResource.getAssociatedResult());
        }

        if (ssm.getRadiusModel() != null) {
            // now lets do the radius
            TridasRadius origRadius = new TridasRadius();
            ssm.getRadiusModel().populateToTridasRadius(origRadius);

            TridasSample parentSample = sampleResource.getAssociatedResult();

            // sample first
            EntityResource<TridasRadius> radiusResource;
            if (origRadius.getIdentifier() != null) {
                radiusResource = new EntityResource<TridasRadius>(origRadius, TellervoRequestType.UPDATE,
                        TridasRadius.class);
            } else {
                radiusResource = new EntityResource<TridasRadius>(origRadius, parentSample, TridasRadius.class);
            }

            // set up a dialog...
            parentWindow = SwingUtilities.getWindowAncestor(model.getMainView());
            dialog = TellervoResourceAccessDialog.forWindow(parentWindow, radiusResource);

            radiusResource.query();
            dialog.setVisible(true);

            if (!dialog.isSuccessful()) {
                JOptionPane.showMessageDialog(BulkImportModel.getInstance().getMainView(),
                        I18n.getText("error.savingChanges") + "\r\n" + I18n.getText("error") + ": "
                                + dialog.getFailException().getLocalizedMessage(),
                        I18n.getText("error"), JOptionPane.ERROR_MESSAGE);
                continue;
            }
            ssm.getRadiusModel().populateFromTridasRadius(radiusResource.getAssociatedResult());
            ssm.getRadiusModel().setDirty(false);
            tmodel.setSelected(ssm, false);
        }
        i++;
    }
}

From source file:org.tellervo.desktop.tridasv2.ui.ComponentViewer.java

/**
 * Called when someone has made this panel visible
 *//*w ww.  j ava2s  .co m*/
public void notifyPanelVisible() {
    if (loadedComprehensive)
        return;

    loadedComprehensive = true;

    if (sample.getLoader() instanceof TellervoWSILoader) {
        TridasIdentifier identifier = ((TellervoWSILoader) sample.getLoader()).getTridasIdentifier();
        // create a new resource
        SeriesResource resource = new SeriesResource(identifier, EntityType.MEASUREMENT_SERIES,
                TellervoRequestType.READ);

        // flag it as comprehensive
        resource.setProperty(TellervoResourceProperties.ENTITY_REQUEST_FORMAT,
                TellervoRequestFormat.COMPREHENSIVE);
        resource.setOwnerWindow(SwingUtilities.getWindowAncestor(this));

        resource.addResourceEventListener(this);
        resource.query();

        setStatus("Loading comprehensive series...", true);

        return;
    }

    setStatus("Cannot load comprehensive view for this series.", false);
}

From source file:org.trzcinka.intellitrac.view.toolwindow.tickets.ticket_editor.BaseTicketEditorForm.java

public BaseTicketEditorForm() {
    ticketsModel.getCurrentTicketModel().addListener(this);
    submitChangesButton.addActionListener(retrieveSubmitButtonActionListener());
    changeHistoryButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Window window = SwingUtilities.getWindowAncestor(rootComponent);
            TicketChangesHistoryPopup dialog = new TicketChangesHistoryPopup(window,
                    ticketsModel.getCurrentTicketModel().getCurrentTicket().getChanges());
            dialog.pack();//from www. j a v  a  2s .  co  m
            dialog.setLocationRelativeTo(null);
            dialog.setVisible(true);
            dialog.dispose();
        }
    });
    downloadButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Attachment attachment = (Attachment) attachmentsList.getSelectedValue();
            OutputStream stream = null;
            if (attachment != null) {
                try {
                    byte[] body = gateway.retrieveAttachment(
                            ticketsModel.getCurrentTicketModel().getCurrentTicket().getId(),
                            attachment.getFileName());
                    JFileChooser fc = new JFileChooser();
                    File dir = fc.getCurrentDirectory();
                    fc.setSelectedFile(new File(dir, attachment.getFileName()));
                    int save = fc.showSaveDialog(rootComponent);

                    if (save == JFileChooser.APPROVE_OPTION) {
                        File file = fc.getSelectedFile();
                        stream = new FileOutputStream(file);
                        IOUtils.write(body, stream);
                    }
                } catch (ConnectionFailedException e1) {
                    TracGatewayLocator.handleConnectionProblem();
                } catch (IOException e1) {
                    logger.error("Could not save file", e1);
                } finally {
                    IOUtils.closeQuietly(stream);
                }
            }
        }
    });
    showDescriptionButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Attachment attachment = (Attachment) attachmentsList.getSelectedValue();
            if (attachment != null) {
                JOptionPane popup = new AttachmentDescriptionPopup(attachment.getDescription());
                JDialog dialog = popup.createDialog(null,
                        MessageFormat.format(
                                bundle.getString("tool_window.tickets.ticket_editor.attachments.popup_title"),
                                attachment.getFileName()));
                dialog.setVisible(true);
                dialog.dispose();
            }
        }
    });
    attachmentsList.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            Attachment selected = (Attachment) attachmentsList.getSelectedValue();
            if (selected == null) {
                downloadButton.setEnabled(false);
                showDescriptionButton.setEnabled(false);
            } else {
                downloadButton.setEnabled(true);
                if (!(StringUtils.isEmpty(selected.getDescription()))) {
                    showDescriptionButton.setEnabled(true);
                }
            }
        }
    });
    newAttachmentButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Window window = SwingUtilities.getWindowAncestor(rootComponent);
            NewAttachmentPopup dialog = new NewAttachmentPopup(window,
                    ticketsModel.getCurrentTicketModel().getCurrentTicket().getId());
            dialog.pack();
            dialog.setLocationRelativeTo(null);
            dialog.setVisible(true);
            dialog.dispose();
            synchronizeTicket();
        }
    });
    synchronizeButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            synchronizeTicket();
        }
    });
}