Example usage for org.xml.sax SAXException getMessage

List of usage examples for org.xml.sax SAXException getMessage

Introduction

In this page you can find the example usage for org.xml.sax SAXException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Return a detail message for this exception.

Usage

From source file:org.soyatec.windowsazure.management.ServiceManagementRest.java

private String encodeBase64(String content) {
    try {/*from   w  w  w  . j a v  a  2s . c  o m*/
        content = content.replaceAll("\r\n", "");
        byte[] bytes = content.getBytes("utf-8");
        XmlValidationUtil.validate(bytes,
                this.getClass().getClassLoader().getResource(SERVICE_CONFIGURATION_SCHEMA_XSD));

        return Base64.encode(bytes);
    } catch (IOException e) {
        throw new IllegalStateException("Configuration file is not valid, " + e.getMessage());
    } catch (SAXException ex) {
        throw new IllegalStateException("Configuration file is not valid, " + ex.getMessage());
    }
}

From source file:it.imtech.metadata.MetaUtility.java

public void findLastContribute(String panelname) {
    try {//from   ww  w  . j av a  2 s .com
        int tmpseq;
        last_contribute = 0;

        DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc;

        File s = new File(Globals.DUPLICATION_FOLDER_SEP + "session" + panelname);

        String expression = "//*[@ID='11']";
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();

        doc = dBuilder.parse(s.getAbsolutePath());

        NodeList nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);

        for (int i = 0; i < nodeList.getLength() && nodeList.getLength() > 1; i++) {
            NamedNodeMap attr = nodeList.item(i).getAttributes();
            Node nodeAttr = attr.getNamedItem("sequence");
            tmpseq = Integer.parseInt(nodeAttr.getNodeValue());
            System.out.println("contribute sequence: " + tmpseq);
            if (tmpseq > last_contribute) {
                last_contribute = tmpseq;
            }
        }

    } catch (SAXException ex) {
        logger.error(ex.getMessage());
    } catch (IOException ex) {
        logger.error(ex.getMessage());
    } catch (XPathExpressionException ex) {
        logger.error(ex.getMessage());
    } catch (ParserConfigurationException ex) {
        logger.error(ex.getMessage());
    }
}

From source file:ch.entwine.weblounge.common.impl.site.SiteImpl.java

/**
 * Loads and registers the integration tests that are found in the bundle at
 * the given location./*from   ww w .ja v  a 2  s .c  o m*/
 * 
 * @param dir
 *          the directory containing the test files
 */
private List<IntegrationTest> loadIntegrationTestDefinitions(String dir) {
    Enumeration<?> entries = bundleContext.getBundle().findEntries(dir, "*.xml", true);

    // Schema validator setup
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL schemaUrl = SiteImpl.class.getResource("/xsd/test.xsd");
    Schema testSchema = null;
    try {
        testSchema = schemaFactory.newSchema(schemaUrl);
    } catch (SAXException e) {
        logger.error("Error loading XML schema for test definitions: {}", e.getMessage());
        return Collections.emptyList();
    }

    // Module.xml document builder setup
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setSchema(testSchema);
    docBuilderFactory.setNamespaceAware(true);

    // The list of tests
    List<IntegrationTest> tests = new ArrayList<IntegrationTest>();

    while (entries != null && entries.hasMoreElements()) {
        URL entry = (URL) entries.nextElement();

        // Validate and read the module descriptor
        ValidationErrorHandler errorHandler = new ValidationErrorHandler(entry);
        DocumentBuilder docBuilder;

        try {
            docBuilder = docBuilderFactory.newDocumentBuilder();
            docBuilder.setErrorHandler(errorHandler);
            Document doc = docBuilder.parse(entry.openStream());
            if (errorHandler.hasErrors()) {
                logger.warn("Error parsing integration test {}: XML validation failed", entry);
                continue;
            }
            IntegrationTestGroup test = IntegrationTestParser.fromXml(doc.getFirstChild());
            test.setSite(this);
            test.setGroup(getName());
            tests.add(test);
        } catch (SAXException e) {
            throw new IllegalStateException(e);
        } catch (IOException e) {
            throw new IllegalStateException(e);
        } catch (ParserConfigurationException e) {
            throw new IllegalStateException(e);
        }
    }

    return tests;
}

From source file:com.paniclauncher.data.Settings.java

/**
 * Loads the Addons for use in the Launcher
 *//*w  ww  .j  a  va  2s .  co m*/
private void loadAddons() {
    if (this.addons.size() != 0) {
        this.addons = new ArrayList<Addon>();
    }
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new File(configsDir, "addons.xml"));
        document.getDocumentElement().normalize();
        NodeList nodeList = document.getElementsByTagName("addon");
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;
                int id = Integer.parseInt(element.getAttribute("id"));
                String name = element.getAttribute("name");
                String[] versions;
                if (element.getAttribute("versions").isEmpty()) {
                    versions = new String[0];
                } else {
                    versions = element.getAttribute("versions").split(",");
                }
                String description = element.getAttribute("description");
                Pack forPack;
                Pack pack = getPackByID(id);
                if (pack != null) {
                    forPack = pack;
                } else {
                    log("Addon " + name + " is not available for any packs!", LogMessageType.warning, false);
                    continue;
                }
                Addon addon = new Addon(id, name, versions, description, forPack);
                addons.add(addon);
            }
        }
    } catch (SAXException e) {
        this.console.logStackTrace(e);
    } catch (ParserConfigurationException e) {
        this.console.logStackTrace(e);
    } catch (IOException e) {
        this.console.logStackTrace(e);
    } catch (InvalidPack e) {
        log(e.getMessage(), LogMessageType.error, false);
    }
}

From source file:eu.apenet.dpt.standalone.gui.DataPreparationToolGUI.java

private void wireUp() {
    fileItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            if (actionEvent.getSource() == fileItem) {
                currentLocation = new File(retrieveFromDb.retrieveOpenLocation());
                fileChooser.setCurrentDirectory(currentLocation);
                int returnedVal = fileChooser.showOpenDialog(getParent());

                if (returnedVal == JFileChooser.APPROVE_OPTION) {
                    currentLocation = fileChooser.getCurrentDirectory();
                    retrieveFromDb.saveOpenLocation(currentLocation.getAbsolutePath());

                    RootPaneContainer root = (RootPaneContainer) getRootPane().getTopLevelAncestor();
                    root.getGlassPane().setCursor(WAIT_CURSOR);
                    root.getGlassPane().setVisible(true);

                    File[] files = fileChooser.getSelectedFiles();
                    for (File file : files) {
                        if (file.isDirectory()) {
                            File[] fileArray = file.listFiles();
                            Arrays.sort(fileArray, new FileNameComparator());
                            for (File children : fileArray) {
                                if (isCorrect(children)) {
                                    xmlEadListModel.addFile(children);
                                }//ww  w .  ja va2 s . c  o m
                            }
                        } else {
                            if (isCorrect(file)) {
                                xmlEadListModel.addFile(file);
                            }
                        }
                    }

                    root.getGlassPane().setCursor(DEFAULT_CURSOR);
                    root.getGlassPane().setVisible(false);
                }
            }
        }
    });
    repositoryCodeItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            createOptionPaneForRepositoryCode();
        }
    });
    countryCodeItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            createOptionPaneForCountryCode();
        }
    });
    checksLoadingFilesItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            createOptionPaneForChecksLoadingFiles();
        }
    });
    createEag2012FromExistingEag2012.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser eagFileChooser = new JFileChooser();
            eagFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            eagFileChooser.setMultiSelectionEnabled(false);
            eagFileChooser.setCurrentDirectory(new File(retrieveFromDb.retrieveOpenLocation()));
            if (eagFileChooser.showOpenDialog(getParent()) == JFileChooser.APPROVE_OPTION) {
                currentLocation = eagFileChooser.getCurrentDirectory();
                retrieveFromDb.saveOpenLocation(currentLocation.getAbsolutePath());

                File eagFile = eagFileChooser.getSelectedFile();
                if (!Eag2012Frame.isUsed()) {
                    try {
                        if (ReadXml.isXmlFile(eagFile, "eag")) {
                            new Eag2012Frame(eagFile, getContentPane().getSize(),
                                    (ProfileListModel) getXmlEadList().getModel(), labels);
                        } else {
                            JOptionPane.showMessageDialog(rootPane,
                                    labels.getString("eag2012.errors.notAnEagFile"));
                        }
                    } catch (SAXException ex) {
                        if (ex instanceof SAXParseException) {
                            JOptionPane.showMessageDialog(rootPane,
                                    labels.getString("eag2012.errors.notAnEagFile"));
                        }
                        java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName())
                                .log(java.util.logging.Level.SEVERE, null, ex);
                    } catch (IOException ex) {
                        java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName())
                                .log(java.util.logging.Level.SEVERE, null, ex);
                    } catch (ParserConfigurationException ex) {
                        java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName())
                                .log(java.util.logging.Level.SEVERE, null, ex);
                    } catch (Exception ex) {
                        try {
                            JOptionPane.showMessageDialog(rootPane, labels.getString(ex.getMessage()));
                        } catch (Exception ex1) {
                            JOptionPane.showMessageDialog(rootPane, "Error...");
                        }
                    }
                }
            }
        }
    });
    createEag2012FromScratch.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (!Eag2012Frame.isUsed()) {
                new Eag2012Frame(getContentPane().getSize(), (ProfileListModel) getXmlEadList().getModel(),
                        labels, retrieveFromDb.retrieveCountryCode(), retrieveFromDb.retrieveRepositoryCode());
            }
        }
    });
    digitalObjectTypeItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (!DigitalObjectAndRightsOptionFrame.isInUse()) {
                JFrame DigitalObjectAndRightsOptionFrame = new DigitalObjectAndRightsOptionFrame(labels,
                        retrieveFromDb);

                DigitalObjectAndRightsOptionFrame.setPreferredSize(new Dimension(
                        getContentPane().getWidth() * 3 / 8, getContentPane().getHeight() * 3 / 4));
                DigitalObjectAndRightsOptionFrame.setLocation(getContentPane().getWidth() / 8,
                        getContentPane().getHeight() / 8);

                DigitalObjectAndRightsOptionFrame.pack();
                DigitalObjectAndRightsOptionFrame.setVisible(true);
            }
        }
    });
    defaultSaveFolderItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            JFileChooser defaultSaveFolderChooser = new JFileChooser();
            defaultSaveFolderChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            defaultSaveFolderChooser.setMultiSelectionEnabled(false);
            defaultSaveFolderChooser.setCurrentDirectory(new File(retrieveFromDb.retrieveDefaultSaveFolder()));
            if (defaultSaveFolderChooser.showOpenDialog(getParent()) == JFileChooser.APPROVE_OPTION) {
                File directory = defaultSaveFolderChooser.getSelectedFile();
                if (directory.canWrite() && DirectoryPermission.canWrite(directory)) {
                    retrieveFromDb.saveDefaultSaveFolder(directory + "/");
                } else {
                    createErrorOrWarningPanel(new Exception(labels.getString("error.directory.nowrites")),
                            false, labels.getString("error.directory.nowrites"), getContentPane());
                }
            }
        }
    });
    listDateConversionRulesItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            JDialog dateConversionRulesDialog = new DateConversionRulesDialog(labels, retrieveFromDb);

            dateConversionRulesDialog.setPreferredSize(
                    new Dimension(getContentPane().getWidth() * 3 / 8, getContentPane().getHeight() * 7 / 8));
            dateConversionRulesDialog.setLocation(getContentPane().getWidth() / 8,
                    getContentPane().getHeight() / 8);

            dateConversionRulesDialog.pack();
            dateConversionRulesDialog.setVisible(true);

        }
    });
    edmGeneralOptionsItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (!EdmGeneralOptionsFrame.isInUse()) {
                JFrame edmGeneralOptionsFrame = new EdmGeneralOptionsFrame(labels, retrieveFromDb);

                edmGeneralOptionsFrame.setPreferredSize(new Dimension(getContentPane().getWidth() * 3 / 8,
                        getContentPane().getHeight() * 3 / 8));
                edmGeneralOptionsFrame.setLocation(getContentPane().getWidth() / 8,
                        getContentPane().getHeight() / 8);

                edmGeneralOptionsFrame.pack();
                edmGeneralOptionsFrame.setVisible(true);
            }
        }
    });
    closeSelectedItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            xmlEadListModel.removeFiles(xmlEadList.getSelectedValues());
        }
    });
    saveSelectedItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String defaultOutputDirectory = retrieveFromDb.retrieveDefaultSaveFolder();
            boolean isMultipleFiles = xmlEadList.getSelectedIndices().length > 1;

            RootPaneContainer root = (RootPaneContainer) getRootPane().getTopLevelAncestor();
            root.getGlassPane().setCursor(WAIT_CURSOR);
            root.getGlassPane().setVisible(true);

            for (Object selectedValue : xmlEadList.getSelectedValues()) {
                File selectedFile = (File) selectedValue;
                String filename = selectedFile.getName();
                FileInstance fileInstance = fileInstances.get(filename);
                String filePrefix = fileInstance.getFileType().getFilePrefix();

                //todo: do we really need this?
                filename = filename.startsWith("temp_") ? filename.replace("temp_", "") : filename;

                filename = !filename.endsWith(".xml") ? filename + ".xml" : filename;

                if (!fileInstance.isValid()) {
                    filePrefix = "NOT_" + filePrefix;
                }

                if (fileInstance.getLastOperation().equals(FileInstance.Operation.EDIT_TREE)) {
                    TreeTableModel treeTableModel = tree.getTreeTableModel();
                    Document document = (Document) treeTableModel.getRoot();
                    try {
                        File file2 = new File(defaultOutputDirectory + filePrefix + "_" + filename);
                        File filetemp = new File(Utilities.TEMP_DIR + "temp_" + filename);
                        TransformerFactory tf = TransformerFactory.newInstance();
                        Transformer output = tf.newTransformer();
                        output.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes");
                        output.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

                        DOMSource domSource = new DOMSource(document.getFirstChild());
                        output.transform(domSource, new StreamResult(filetemp));
                        output.transform(domSource, new StreamResult(file2));

                        fileInstance.setLastOperation(FileInstance.Operation.SAVE);
                        fileInstance.setCurrentLocation(filetemp.getAbsolutePath());
                    } catch (Exception ex) {
                        createErrorOrWarningPanel(ex, true, labels.getString("errorSavingTreeXML"),
                                getContentPane());
                    }
                } else if (fileInstance.isConverted()) {
                    try {
                        File newFile = new File(defaultOutputDirectory + filePrefix + "_" + filename);
                        FileUtils.copyFile(new File(fileInstance.getCurrentLocation()), newFile);
                        fileInstance.setLastOperation(FileInstance.Operation.SAVE);
                        //                            fileInstance.setCurrentLocation(newFile.getAbsolutePath());
                    } catch (IOException ioe) {
                        LOG.error("Error when saving file", ioe);
                    }
                } else {
                    try {
                        File newFile = new File(defaultOutputDirectory + filePrefix + "_" + filename);
                        FileUtils.copyFile(selectedFile, newFile);
                        fileInstance.setLastOperation(FileInstance.Operation.SAVE);
                        //                            fileInstance.setCurrentLocation(newFile.getAbsolutePath());
                    } catch (IOException ioe) {
                        LOG.error("Error when saving file", ioe);
                    }
                }
            }

            root.getGlassPane().setCursor(DEFAULT_CURSOR);
            root.getGlassPane().setVisible(false);

            if (isMultipleFiles) {
                JOptionPane.showMessageDialog(getContentPane(),
                        MessageFormat.format(labels.getString("filesInOutput"), defaultOutputDirectory) + ".",
                        labels.getString("fileSaved"), JOptionPane.INFORMATION_MESSAGE, Utilities.icon);
            } else {
                JOptionPane.showMessageDialog(getContentPane(),
                        MessageFormat.format(labels.getString("fileInOutput"), defaultOutputDirectory) + ".",
                        labels.getString("fileSaved"), JOptionPane.INFORMATION_MESSAGE, Utilities.icon);
            }
            xmlEadList.updateUI();
        }
    });
    saveMessageReportItem.addActionListener(
            new MessageReportActionListener(retrieveFromDb, this, fileInstances, labels, this));
    sendFilesWebDAV.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    });
    quitItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    });
    xsltItem.addActionListener(new XsltAdderActionListener(this, labels));
    xsdItem.addActionListener(new XsdAdderActionListener(this, labels, retrieveFromDb));
    if (Utilities.isDev) {
        databaseItem.addActionListener(new DatabaseCheckerActionListener(retrieveFromDb, getContentPane()));
    }
    xmlEadList.addMouseListener(new ListMouseAdapter(xmlEadList, xmlEadListModel, deleteFileItem, this));
    xmlEadList.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                if (xmlEadList.getSelectedValues() != null && xmlEadList.getSelectedValues().length != 0) {
                    if (xmlEadList.getSelectedValues().length > 1) {
                        //                            convertAndValidateBtn.setEnabled(true);
                        //                            validateSelectionBtn.setEnabled(true);
                        //                            if (isValidated(xmlEadList)) {
                        //                                convertEdmSelectionBtn.setEnabled(true);
                        //                            } else {
                        //                                convertEdmSelectionBtn.setEnabled(false);
                        //                            }
                        //                            disableAllBtnAndItems();
                        saveMessageReportItem.setEnabled(true);
                        changeInfoInGUI("");
                    } else {
                        //                            convertAndValidateBtn.setEnabled(false);
                        //                            validateSelectionBtn.setEnabled(false);
                        //                            convertEdmSelectionBtn.setEnabled(false);
                        changeInfoInGUI(((File) xmlEadList.getSelectedValue()).getName());
                        if (apePanel.getApeTabbedPane().getSelectedIndex() == APETabbedPane.TAB_EDITION) {
                            apePanel.getApeTabbedPane()
                                    .createEditionTree(((File) xmlEadList.getSelectedValue()));
                            if (tree != null) {
                                FileInstance fileInstance = fileInstances
                                        .get(((File) getXmlEadList().getSelectedValue()).getName());
                                tree.addMouseListener(new PopupMouseListener(tree, getDataPreparationToolGUI(),
                                        getContentPane(), fileInstance));
                            }
                        }
                        disableTabFlashing();
                    }
                    checkHoldingsGuideButton();
                } else {
                    //                        convertAndValidateBtn.setEnabled(false);
                    //                        validateSelectionBtn.setEnabled(false);
                    //                        convertEdmSelectionBtn.setEnabled(false);
                    createHGBtn.setEnabled(false);
                    analyzeControlaccessBtn.setEnabled(false);
                    changeInfoInGUI("");
                }
            }
        }

        private boolean isValidated(JList xmlEadList) {
            for (Object selectedValue : xmlEadList.getSelectedValues()) {
                File selectedFile = (File) selectedValue;
                String filename = selectedFile.getName();
                FileInstance fileInstance = fileInstances.get(filename);
                if (!fileInstance.isValid()) {
                    return false;
                }
            }
            return true;
        }
    });

    summaryWindowItem.addActionListener(new TabItemActionListener(apePanel, APETabbedPane.TAB_SUMMARY));
    validationWindowItem.addActionListener(new TabItemActionListener(apePanel, APETabbedPane.TAB_VALIDATION));
    conversionWindowItem.addActionListener(new TabItemActionListener(apePanel, APETabbedPane.TAB_CONVERSION));
    edmConversionWindowItem.addActionListener(new TabItemActionListener(apePanel, APETabbedPane.TAB_EDM));
    editionWindowItem.addActionListener(new TabItemActionListener(apePanel, APETabbedPane.TAB_EDITION));

    internetApexItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            BareBonesBrowserLaunch.openURL("http://www.apex-project.eu/");
        }
    });

    /**
     * Option Edit apeEAC-CPF file in the menu
     */

    this.editEacCpfFile.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser eacFileChooser = new JFileChooser();
            eacFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            eacFileChooser.setMultiSelectionEnabled(false);
            eacFileChooser.setCurrentDirectory(new File(retrieveFromDb.retrieveOpenLocation()));
            if (eacFileChooser.showOpenDialog(getParent()) == JFileChooser.APPROVE_OPTION) {
                currentLocation = eacFileChooser.getCurrentDirectory();
                retrieveFromDb.saveOpenLocation(currentLocation.getAbsolutePath());

                File eacFile = eacFileChooser.getSelectedFile();
                if (!EacCpfFrame.isUsed()) {
                    try {
                        if (ReadXml.isXmlFile(eacFile, "eac-cpf")) {
                            new EacCpfFrame(eacFile, true, getContentPane().getSize(),
                                    (ProfileListModel) getXmlEadList().getModel(), labels);
                        } else {
                            JOptionPane.showMessageDialog(rootPane,
                                    labels.getString("eaccpf.error.notAnEacCpfFile"));
                        }
                    } catch (SAXException ex) {
                        if (ex instanceof SAXParseException) {
                            JOptionPane.showMessageDialog(rootPane,
                                    labels.getString("eaccpf.error.notAnEacCpfFile"));
                        }
                        java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName())
                                .log(java.util.logging.Level.SEVERE, null, ex);
                    } catch (IOException ex) {
                        java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName())
                                .log(java.util.logging.Level.SEVERE, null, ex);
                    } catch (ParserConfigurationException ex) {
                        java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName())
                                .log(java.util.logging.Level.SEVERE, null, ex);
                    } catch (Exception ex) {
                        try {
                            JOptionPane.showMessageDialog(rootPane, labels.getString(ex.getMessage()));
                        } catch (Exception ex1) {
                            JOptionPane.showMessageDialog(rootPane, "Error...");
                        }
                    }
                }
            }
        }
    });

    /**
     * Option Create apeEAC-CPF in the menu
     */
    this.createEacCpf.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (!EacCpfFrame.isUsed()) {
                EacCpfFrame eacCpfFrame = new EacCpfFrame(getContentPane().getSize(),
                        (ProfileListModel) getXmlEadList().getModel(), labels,
                        retrieveFromDb.retrieveCountryCode(), retrieveFromDb.retrieveRepositoryCode(), null,
                        null, null);
            }
        }
    });

}

From source file:de.interactive_instruments.ShapeChange.Target.FeatureCatalogue.FeatureCatalogue.java

private void PrintClass(ClassInfo ci, boolean onlyProperties, Operation op, PackageInfo pix) {

    if (!ExportClass(ci, onlyProperties, op))
        return;/*from   w  w  w . j a  v  a2 s.c om*/

    try {

        if (onlyProperties) {

            String ciid = "_C" + ci.id();
            ciid = options.internalize(ciid);

            writer.startElement("FeatureType", "id", ciid, op);

            PrintDescriptors(ci, true, op);

            // NOTE: the Differ currently does not check abstractness
            if (ci.isAbstract()) {
                writer.dataElement("isAbstract", "1");
            }

            for (String t : ci.supertypes()) {

                ClassInfo cix = lookupClassById(t);

                if (cix != null) {

                    String name = cix.name();

                    String cixid = "_C" + cix.id();
                    cixid = options.internalize(cixid);

                    // check for insertion
                    boolean inserted = false;
                    Operation opForGeneralization = op;
                    if (hasDiff(ci, ElementType.SUPERTYPE, Operation.INSERT, cix)) {
                        name = "[[ins]]" + name + "[[/ins]]";
                        inserted = true;
                        opForGeneralization = Operation.INSERT;
                    }

                    if (inserted || !Inherit || cix.category() != Options.MIXIN) {

                        name = options.internalize(name);

                        writer.dataElement("subtypeOf", cix.name(), "idref", cixid, opForGeneralization);
                    }
                }
            }
            // Diff: check for potential deletions of supertypes
            if (hasDiff(ci, ElementType.SUPERTYPE, Operation.DELETE)) {

                for (DiffElement diff : getDiffs(ci, ElementType.SUPERTYPE, Operation.DELETE)) {

                    String nameOfDeletedSupertype = "[[del]]" + diff.subElement.name() + "[[/del]]";

                    String supertypeId = diff.subElement.id();

                    /*
                     * Don't simply use the id from the diff's subElement as
                     * reference. Rather, try to look up the class in the
                     * input model.
                     */
                    ClassInfo supertype = lookupClassById(supertypeId);

                    String cixid = "_C" + supertype.id();
                    cixid = options.internalize(cixid);

                    writer.dataElement("subtypeOf", nameOfDeletedSupertype, "idref", cixid, Operation.DELETE);
                }
            }

            PrintProperties(ci, true, op);
            /*
             * TODO PrintOperations true;
             */

            writer.emptyElement("package", "idref", "_P" + pix.id());

            switch (ci.category()) {
            case Options.FEATURE:
            case Options.OKSTRAFID:

                String text = featureTerm + " Type";
                text = options.internalize(text);

                writer.dataElement("type", text, op);

                break;
            case Options.OBJECT:
                writer.dataElement("type", "Object Type", op);
                break;
            case Options.OKSTRAKEY:
            case Options.DATATYPE:
                writer.dataElement("type", "Data Type", op);
                break;
            case Options.UNION:
                writer.dataElement("type", "Union Data Type", op);
                break;
            }

            String s;
            for (Constraint ocl : ci.constraints()) {

                writer.startElement("constraint");

                writer.dataElement("name", ocl.name());

                s = ocl.text();
                String description = null;
                String expression = null;
                if (s != null && s.contains("/*") && s.contains("*/")) {
                    String[] sa = s.split("\\*/");
                    description = sa[0].replaceFirst("/\\*", "").trim();
                    expression = sa[1].trim();
                } else {
                    expression = s;
                }

                if (description != null && description.length() > 0) {
                    writer.dataElement("description", description);
                }

                if (expression != null && expression.length() > 0) {
                    writer.dataElement("expression", expression);
                }

                writer.endElement("constraint");
            }

            s = ci.taggedValue("alwaysVoid");
            if (s != null && s.length() > 0) {
                writer.startElement("constraint");
                writer.dataElement("description", "Properties that are always void: " + s);
                writer.endElement("constraint");
            }
            s = ci.taggedValue("neverVoid");
            if (s != null && s.length() > 0) {
                writer.startElement("constraint");
                writer.dataElement("description", "Properties that are never void: " + s);
                writer.endElement("constraint");
            }
            s = ci.taggedValue("appliesTo");
            if (s != null && s.length() > 0) {
                writer.startElement("constraint");
                writer.dataElement("description", "Applies to the following network elements: " + s);
                writer.endElement("constraint");
            }

            writer.startElement("taggedValues");

            s = ci.taggedValue("name");
            if (s != null && s.trim().length() > 0) {
                writer.dataElement("name", PrepareToPrint(s), op);
            }
            writer.endElement("taggedValues");

            if (ci.getDiagrams() != null) {
                appendImageInfo(ci.getDiagrams());
            }

            writer.endElement("FeatureType");
        }

        PrintProperties(ci, false, op);
        /*
         * TODO PrintOperations false;
         */

    } catch (SAXException e) {

        String m = e.getMessage();
        if (m != null) {
            result.addError(m);
        }
        e.printStackTrace(System.err);
    }
}

From source file:i5.las2peer.services.mobsos.SurveyService.java

/**
 * TODO: write documentation//from  w  w  w. ja  v a2 s  .  com
 * 
 * @param id
 * @param answerXml
 * @return
 */
@POST
@Consumes(MediaType.TEXT_XML)
@Path("surveys/{id}/responses")
public HttpResponse submitSurveyResponseXML(@PathParam("id") int id, @ContentParam String answerXml) {

    String onAction = "submitting response to survey " + id;

    try {
        Document answer;
        // parse answer to XML document incl. validation
        try {
            answer = validateQuestionnaireData(answerXml);
        } catch (SAXException e) {
            HttpResponse result = new HttpResponse("Questionnaire form is invalid! Cause: " + e.getMessage());
            result.setStatus(400);
            return result;
        }

        return submitSurveyResponseJSON(id, convertResponseXMLtoJSON(answer).toJSONString());

    } catch (Exception e) {
        e.printStackTrace();
        return internalError(onAction);
    }
}

From source file:i5.las2peer.services.mobsos.SurveyService.java

/**
 * TODO: write documentation/*  ww w.  ja va2s . c  o m*/
 * @param id
 * @param formXml
 * @return
 */
@PUT
@Consumes(MediaType.TEXT_XML)
@Path("questionnaires/{id}/form")
@Summary("Upload for for given questionnaire.")
@Notes("Requires authentication and ownership of questionnaire.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Questionnaire form upload successful."),
        @ApiResponse(code = 400, message = "Questionnaire form data invalid."),
        @ApiResponse(code = 401, message = "Questionnaire form may only be uploaded by owner. -or- Questionnaire form upload requires authentication."),
        @ApiResponse(code = 404, message = "Questionnaire does not exist.") })
public HttpResponse uploadQuestionnaireForm(@PathParam("id") int id, @ContentParam String formXml) {

    if (getActiveAgent().getId() == getActiveNode().getAnonymous().getId()) {
        HttpResponse noauth = new HttpResponse("Please authenticate to upload questionnaire form!");
        noauth.setStatus(401);
    }

    String onAction = "uploading form for questionnaire " + id;

    try {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rset = null;

        try {

            // 
            int exown = checkExistenceOwnership(id, 1);

            // check if questionnaire exists; if not, return 404.
            if (exown == -1) {
                HttpResponse result = new HttpResponse("Questionnaire " + id + " does not exist.");
                result.setStatus(404);
                return result;
            }
            // if questionnaire exists, check if active agent is owner. if not, return 401.
            else if (exown == 0) {
                HttpResponse result = new HttpResponse(
                        "Form for questionnaire " + id + "  may only be uploaded by its owner.");
                result.setStatus(401);
                return result;
            }

            // before storing to database validate questionnaire form
            try {
                // validate form XML against MobSOS Survey XML Schema. Since the schema also defines valid responses, a next check
                // is needed to make sure the passed and valid XML is a questionnaire form, and not a response. 
                Document form = validateQuestionnaireData(formXml);

                if (!form.getDocumentElement().getNodeName().equals("qu:Questionnaire")) {
                    HttpResponse result = new HttpResponse(
                            "Document is not a questionnaire form! Cause: Document element must be 'qu:Questionnaire'.");
                    result.setStatus(400);
                    return result;
                }

                String lang = form.getDocumentElement().getAttribute("xml:lang");
                //System.out.println("Language detected: " + lang);

            } catch (SAXException e) {

                HttpResponse result = new HttpResponse(
                        "Questionnaire form is invalid! Cause: " + e.getMessage());
                result.setStatus(400);
                return result;
            }

            // store valid form to database
            conn = dataSource.getConnection();
            stmt = conn.prepareStatement("update " + jdbcSchema + ".questionnaire set form=? where id = ?");

            stmt.setString(1, formXml);
            stmt.setInt(2, id);
            stmt.executeUpdate();

            // respond to user
            HttpResponse result = new HttpResponse("Form upload for questionnaire " + id + " successful.");
            result.setStatus(200);
            return result;

        } catch (SQLException | UnsupportedOperationException e) {
            return internalError(onAction);
        } finally {
            try {
                if (rset != null)
                    rset.close();
            } catch (Exception e) {
                e.printStackTrace();
                return internalError(onAction);
            }
            try {
                if (stmt != null)
                    stmt.close();
            } catch (Exception e) {
                e.printStackTrace();
                return internalError(onAction);
            }
            try {
                if (conn != null)
                    conn.close();
            } catch (Exception e) {
                e.printStackTrace();
                return internalError(onAction);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return internalError(onAction);
    }
}

From source file:i5.las2peer.services.mobsos.SurveyService.java

/**
 * TODO: write documentation//from  w  ww  . j a va 2  s.c  o  m
 * 
 * @param id
 * @return
 */
@GET
@Produces(MediaType.TEXT_CSV)
@Path("surveys/{id}/responses")
@Summary("retrieve response data for given survey.")
@Notes("Use resource <i>/surveys</i> to retrieve list of existing surveys.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Survey response data in CSV format."),
        @ApiResponse(code = 404, message = "Survey does not exist -or- No questionnaire defined for survey.") })
public HttpResponse getSurveyResponses(@PathParam("id") int id,
        @QueryParam(name = "sepline", defaultValue = "0") int sepline,
        @QueryParam(name = "sep", defaultValue = ",") String sep) {

    String onAction = "retrieving responses for survey " + id;

    try {
        int exown = checkExistenceOwnership(id, 0);

        // check if survey exists. If not, respond with not found.
        if (exown == -1) {
            HttpResponse result = new HttpResponse("Survey " + id + " does not exist.");
            result.setStatus(404);
            return result;
        }

        // check if a questionnaire for survey is defined. If not, respond with not found.
        int qid = getQuestionnaireIdForSurvey(id);
        if (qid == -1) {
            HttpResponse result = new HttpResponse("No questionnaire defined for survey " + id + "!");
            result.setStatus(404);
            return result;
        }

        // retrieve questionnaire form for survey to do answer validation
        HttpResponse r = downloadQuestionnaireForm(qid);

        // if questionnaire form does not exist, pass on response containing error status
        if (200 != r.getStatus()) {
            return r;
        }

        // parse form to XML document incl. validation; will later on be necessary to build query for
        // questionnaire answer table
        Document form;

        try {
            form = validateQuestionnaireData(r.getResult());
        } catch (SAXException e) {
            e.printStackTrace();
            HttpResponse result = new HttpResponse("Questionnaire form is invalid! Cause: " + e.getMessage());
            result.setStatus(400);
            return result;
        }

        // now check, if a survey response view exists. If not, create it.
        if (!existsResponseView(id)) {
            createResponseView(id, form);
        }

        // execute generated query
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rset = null;

        try {
            conn = dataSource.getConnection();
            stmt = conn.prepareStatement("select * from " + jdbcSchema + ".responses_survey_" + id);
            rset = stmt.executeQuery();

            // format and return result
            String res = createCSVQuestionnaireResult(rset, sep);

            if (sepline > 0) {
                // add separator declaration
                res = "sep=" + sep + "\r\n" + res;
            }

            HttpResponse result = new HttpResponse(res);
            result.setStatus(200);
            return result;

        } catch (SQLException | UnsupportedOperationException e) {
            return internalError(onAction);
        } finally {
            try {
                if (rset != null)
                    rset.close();
            } catch (Exception e) {
                e.printStackTrace();
                return internalError(onAction);
            }
            try {
                if (stmt != null)
                    stmt.close();
            } catch (Exception e) {
                e.printStackTrace();
                return internalError(onAction);
            }
            try {
                if (conn != null)
                    conn.close();
            } catch (Exception e) {
                e.printStackTrace();
                return internalError(onAction);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        return internalError(onAction + "cause: " + e.getMessage());
    }
}

From source file:i5.las2peer.services.mobsos.SurveyService.java

@POST
@Consumes(MediaType.APPLICATION_JSON)/*from w  w  w.ja v  a  2 s .  c o m*/
@Path("surveys/{id}/responses")
@Summary("submit response data to given survey.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Survey response submitted successfully."),
        @ApiResponse(code = 400, message = "Survey response invalid -or- questionnaire form invalid. Cause: ..."),
        @ApiResponse(code = 404, message = "Survey does not exist -or- No questionnaire defined for survey."),
        @ApiResponse(code = 400, message = "Survey response already submitted."), })
public HttpResponse submitSurveyResponseJSON(@PathParam("id") int id, @ContentParam String answerJSON) {
    Date now = new Date();
    String onAction = "submitting response to survey " + id;
    try {

        // retrieve survey by id;
        HttpResponse rs = getSurvey(id);
        if (rs.getStatus() != 200) {
            return rs;
        }

        JSONObject s = (JSONObject) JSONValue.parse(rs.getResult());

        // check if survey expired/not started
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        df.setTimeZone(TimeZone.getTimeZone("GMT"));

        Date start = df.parse((String) s.get("start"));
        Date end = df.parse((String) s.get("end"));

        if (now.getTime() > end.getTime()) {
            HttpResponse resp = new HttpResponse("Cannot submit response. Survey expired.");
            resp.setStatus(403);
            return resp;
        } else if (now.getTime() < start.getTime()) {
            HttpResponse resp = new HttpResponse("Cannot submit response. Survey has not begun, yet.");
            resp.setStatus(403);
            return resp;
        }

        // check for questionnaire form
        int qid = Integer.parseInt(s.get("qid") + "");

        if (qid == -1) {
            HttpResponse result = new HttpResponse("No questionnaire defined for survey " + id + "!");
            result.setStatus(404);
            return result;
        }

        // retrieve questionnaire form for survey to do answer validation
        HttpResponse r = downloadQuestionnaireForm(qid);

        if (200 != r.getStatus()) {
            // if questionnaire form does not exist, pass on response containing error status
            return r;
        }

        Document form;
        JSONObject answer;

        // parse form to XML document incl. validation
        try {
            form = validateQuestionnaireData(r.getResult());
        } catch (SAXException e) {
            HttpResponse result = new HttpResponse("Questionnaire form is invalid! Cause: " + e.getMessage());
            result.setStatus(400);
            return result;
        }

        try {
            //System.out.println(answerJSON);

            answer = (JSONObject) JSONValue.parseWithException(answerJSON);
        } catch (ParseException e) {
            HttpResponse result = new HttpResponse(
                    "Survey response is not valid JSON! Cause: " + e.getMessage());
            result.setStatus(400);
            return result;
        }

        JSONObject answerFieldTable;

        // validate if answer matches form.
        try {
            answerFieldTable = validateResponse(form, answer);
        } catch (IllegalArgumentException e) {
            HttpResponse result = new HttpResponse("Survey response is invalid! Cause: " + e.getMessage());
            result.setStatus(400);
            return result;
        }

        // after all validation finally persist survey response in database
        int surveyId = id;

        String sub = (String) getActiveUserInfo().get("sub");

        if (getActiveAgent().getId() == getActiveNode().getAnonymous().getId()) {
            sub += now.getTime();
        }

        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rset = null;

        try {
            conn = dataSource.getConnection();
            stmt = conn.prepareStatement(
                    "insert into " + jdbcSchema + ".response(uid,sid,qkey,qval,time) values (?,?,?,?,?)");

            Iterator<String> it = answerFieldTable.keySet().iterator();
            while (it.hasNext()) {

                String qkey = it.next();
                String qval = "" + answerFieldTable.get(qkey);

                stmt.setString(1, sub);
                stmt.setInt(2, surveyId);
                stmt.setString(3, qkey);
                stmt.setString(4, qval);
                stmt.setTimestamp(5, new Timestamp(now.getTime()));
                stmt.addBatch();

            }
            stmt.executeBatch();

            HttpResponse result = new HttpResponse("Response to survey " + id + " submitted successfully.");
            result.setStatus(200);
            return result;

        } catch (SQLException | UnsupportedOperationException e) {
            if (0 <= e.getMessage().indexOf("Duplicate")) {
                HttpResponse result = new HttpResponse("Survey response already submitted!");
                result.setStatus(409);
                return result;
            } else {
                e.printStackTrace();
                return internalError(onAction);
            }
        } finally {
            try {
                if (rset != null)
                    rset.close();
            } catch (Exception e) {
                e.printStackTrace();
                return internalError(onAction);
            }
            try {
                if (stmt != null)
                    stmt.close();
            } catch (Exception e) {
                e.printStackTrace();
                return internalError(onAction);
            }
            try {
                if (conn != null)
                    conn.close();
            } catch (Exception e) {
                e.printStackTrace();
                return internalError(onAction);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return internalError(onAction);
    }
}