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.opencastproject.adminui.endpoint.ToolsEndpoint.java

/**
 * Adds the SMIL file as {@link Catalog} to the media package and sends the updated media package to the archive.
 *
 * @param mediaPackage//  w  ww.j  av  a  2 s .co m
 *          the media package to at the SMIL catalog
 * @param smil
 *          the SMIL catalog
 * @return the updated media package
 * @throws IOException
 *           if the SMIL catalog cannot be read or not be written to the archive
 */
MediaPackage addSmilToArchive(MediaPackage mediaPackage, final Smil smil) throws IOException {
    final String catalogId = "editor-cutting-information";
    Catalog catalog = mediaPackage.getCatalog(catalogId);

    URI smilURI;
    try (InputStream is = IOUtils.toInputStream(smil.toXML(), "UTF-8")) {
        smilURI = workspace.put(mediaPackage.getIdentifier().compact(), smil.getId(), TARGET_FILE_NAME, is);
    } catch (SAXException e) {
        logger.error("Error while serializing the SMIL catalog to XML: {}", e.getMessage());
        throw new IOException(e);
    } catch (JAXBException e) {
        logger.error("Error while serializing the SMIL catalog to XML: {}", e.getMessage());
        throw new IOException(e);
    }

    if (catalog == null) {
        MediaPackageElementBuilder mpeBuilder = MediaPackageElementBuilderFactory.newInstance()
                .newElementBuilder();
        catalog = (Catalog) mpeBuilder.elementFromURI(smilURI, MediaPackageElement.Type.Catalog,
                adminUIConfiguration.getSmilCatalogFlavor());
        mediaPackage.add(catalog);
    }
    catalog.setURI(smilURI);
    catalog.setIdentifier(catalogId);
    catalog.setMimeType(MimeTypes.XML);
    for (String tag : adminUIConfiguration.getSmilCatalogTags()) {
        catalog.addTag(tag);
    }
    // setting the URI to a new source so the checksum will most like be invalid
    catalog.setChecksum(null);

    try {
        // FIXME SWITCHP-333: Start in new thread
        archive.add(mediaPackage);
    } catch (ArchiveException e) {
        logger.error("Error while adding the updated media package ({}) to the archive: {}",
                mediaPackage.getIdentifier(), e.getMessage());
        throw new IOException(e);
    }

    return mediaPackage;
}

From source file:org.openehealth.ipf.commons.xml.XsdValidator.java

/**
 * @param message//from  w w  w  .ja va2 s  . c  o m
 *            the message to be validated
 * @param schemaSource
 *            the XML schema to validate against
 * @return an array of validation exceptions
 */
protected List<ValidationException> doValidate(Source message, String schemaResource) {
    try {
        LOG.debug("Validating XML message");
        Schema schema = obtainSchema(schemaResource);
        javax.xml.validation.Validator validator = schema.newValidator();
        CollectingErrorHandler errorHandler = new CollectingErrorHandler();
        validator.setErrorHandler(errorHandler);
        validator.validate(message);
        List<ValidationException> exceptions = errorHandler.getExceptions();
        if (exceptions.size() > 0) {
            LOG.debug("Message validation found " + exceptions.size() + " problems");
        } else {
            LOG.debug("Message validation successful");
        }
        return exceptions;
    } catch (SAXException e) {
        return Arrays
                .asList(new ValidationException("Unexpected validation failure because " + e.getMessage(), e));
    } catch (IOException e) {
        return Arrays
                .asList(new ValidationException("Unexpected validation failure because " + e.getMessage(), e));
    }
}

From source file:org.openfaces.demo.services.Rules.java

public static void buildSiteRules(ServletContext context) {
    try {//from w ww  .ja  va2 s.  c om
        Digester digester = new Digester();
        digester.setValidating(false);
        digester.addObjectCreate("menu", ArrayList.class);
        digester.addObjectCreate("menu/menuItem", RuleItem.class);

        digester.addSetNext("menu/menuItem", "add");

        digester.addCallMethod("*/menuItem/url", "setUrl", 0);
        digester.addCallMethod("*/menuItem/shortPath", "setShortPath", 0);

        InputStream is = context.getResource("/WEB-INF/menu.xml").openStream();
        rules = (List<RuleItem>) digester.parse(is);

    } catch (IOException e) {
        Log.log(e.getMessage(), e);
    } catch (SAXException ex) {
        Log.log(ex.getMessage(), ex);
    }
}

From source file:org.openhab.ui.cometvisu.internal.servlet.CometVisuServlet.java

/**
 * replaces the dataproviders in/*from www.  ja  v a  2  s . com*/
 * <cometvisu-src>/editor/dataproviders/*.(php|json) +
 *
 * @param file
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
private final void dataProviderService(File file, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("dataprovider '{}' requested", file.getPath());
    List<Object> beans = new ArrayList<Object>();
    String resultString = null;

    File resourceFolder = rootFolder;
    String rel = file.getPath().substring(rootFolder.getPath().length());
    // is CometVisu version >= 0.11 (Qooxdoo based)
    if (rel.startsWith("/source/") || rel.startsWith("/build/")) {
        // Qooxdoo based CometVisu in source/build mode
        // change the folder
        String[] parts = rel.substring(1).split("/");
        resourceFolder = new File(rootFolder, parts[0] + "/resource");
        logger.debug("new resource folder is {}", resourceFolder.getPath());
    }

    if (file.getName().equals("dpt_list.json")) {
        // return all transforms available for openhab
        for (Transform transform : Transform.values()) {
            DataBean bean = new DataBean();
            bean.label = transform.toString().toLowerCase();
            bean.value = "OH:" + bean.label;
            beans.add(bean);
        }
    } else if (file.getName().equals("list_all_addresses.php")) {
        // all item names

        // collect all available transform types
        ArrayList<String> transformTypes = new ArrayList<String>();
        for (Transform transform : Transform.values()) {
            transformTypes.add(transform.toString().toLowerCase());
        }

        Map<String, ArrayList<Object>> groups = new HashMap<String, ArrayList<Object>>();
        for (Item item : this.cometVisuApp.getItemRegistry().getItems()) {
            ItemBean bean = new ItemBean();
            bean.value = item.getName();

            String type = item.getType();
            if (item.getType() == "Group") {
                if (((GroupItem) item).getBaseItem() != null) {
                    type = ((GroupItem) item).getBaseItem().getType();
                } else {
                    continue;
                }
            }
            bean.label = item.getName();
            String transform = type.toLowerCase().replace("Item", "");
            if (transformTypes.contains(transform)) {
                bean.hints.put("transform", "OH:" + transform);
            } else {
                logger.debug("no transform type found for item type {}, skipping this item", type);
                continue;
            }
            if (!groups.containsKey(type)) {
                groups.put(type, new ArrayList<Object>());
            }
            groups.get(type).add(bean);
        }
        resultString = marshalJson(groups);
    } else if (file.getName().equals("list_all_icons.php")) {
        // all item names
        File svgFile = new File(resourceFolder, "icon/knx-uf-iconset.svg");
        if (svgFile.exists()) {
            // extract names from SVG file
            try {
                DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                Document doc = builder.parse(svgFile);
                XPath xpath = XPathFactory.newInstance().newXPath();
                XPathExpression expr = xpath.compile("//symbol/@id");
                NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
                for (int i = 0, len = nl.getLength(); i < len; i++) {
                    Node node = nl.item(i);
                    DataBean bean = new DataBean();
                    bean.label = node.getTextContent();
                    bean.value = node.getTextContent();
                    beans.add(bean);
                }
            } catch (SAXException e) {
                logger.error("error parsing SVG file: {}", e.getMessage(), e);
            } catch (ParserConfigurationException e) {
                logger.error("error extracting items from SVG file: {}", e.getMessage(), e);
            } catch (XPathExpressionException e) {
                logger.error("error extracting items from SVG file: {}", e.getMessage(), e);
            }
        } else {
            File iconDir = new File(resourceFolder, "icon/knx-uf-iconset/128x128_white/");
            if (iconDir.exists() && iconDir.isDirectory()) {
                FilenameFilter filter = new FilenameFilter() {
                    @Override
                    public boolean accept(File dir, String name) {
                        return name.endsWith(".png");
                    }
                };
                File[] icons = iconDir.listFiles(filter);
                Arrays.sort(icons);
                for (File iconFile : icons) {
                    if (iconFile.isFile()) {
                        String iconName = iconFile.getName().replace(".png", "");
                        DataBean bean = new DataBean();
                        bean.label = iconName;
                        bean.value = iconName;
                        beans.add(bean);
                    }
                }
            }
        }
    } else if (file.getName().equals("list_all_plugins.php")) {
        // all plugins
        // all item names
        File pluginDir = new File(resourceFolder, "plugins/");
        File[] plugins = pluginDir.listFiles();
        Arrays.sort(plugins);
        for (File icon : plugins) {
            if (icon.isDirectory()) {
                DataBean bean = new DataBean();
                bean.label = icon.getName();
                bean.value = icon.getName();
                beans.add(bean);
            }
        }

    } else if (file.getName().equals("get_designs.php")) {
        // all designs
        File designDir = new File(resourceFolder, "designs/");
        File[] designs = designDir.listFiles();
        if (designs != null) {
            Arrays.sort(designs);
            for (File design : designs) {
                if (design.isDirectory()) {
                    beans.add(design.getName());
                }
            }
        }

    } else if (file.getName().equals("list_all_rrds.php")) {
        // all item names

    }
    if (beans.size() == 0 && resultString == null) {
        // nothing found try the PHP files
        processPhpRequest(file, request, response);
    } else {
        response.setContentType(MediaType.APPLICATION_JSON);
        if (resultString == null) {
            resultString = marshalJson(beans);
        }
        response.getWriter().write(resultString);
        response.flushBuffer();
    }
}

From source file:org.openmrs.module.radiology.report.template.XsdMrrtReportTemplateValidator.java

/**
 * @see MrrtReportTemplateValidator#validate(String)
 *//*from w ww.ja  v  a 2 s  . c  o  m*/
@Override
public void validate(String mrrtTemplate) throws IOException {

    final Document document = Jsoup.parse(mrrtTemplate, "");
    final Elements metatags = document.getElementsByTag("meta");
    ValidationResult validationResult = metaTagsValidationEngine.run(metatags);

    final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema;
    final Validator validator;
    try (InputStream in = IOUtils.toInputStream(mrrtTemplate)) {
        schema = factory.newSchema(getSchemaFile());
        validator = schema.newValidator();
        validator.setErrorHandler(new ErrorHandler() {

            @Override
            public void warning(SAXParseException exception) throws SAXException {
                log.debug(exception.getMessage(), exception);
                validationResult.addError(exception.getMessage(), "");
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                log.debug(exception.getMessage(), exception);
                validationResult.addError(exception.getMessage(), "");
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                log.debug(exception.getMessage(), exception);
                validationResult.addError(exception.getMessage(), "");
            }
        });
        validator.validate(new StreamSource(in));
        validationResult.assertOk();
    } catch (SAXException e) {
        log.error(e.getMessage(), e);
        throw new APIException("radiology.report.template.validation.error", null, e);
    }
}

From source file:org.opensingular.internal.lib.commons.xml.TestMElement.java

License:asdf

/**
 * Verifica se o parde dispara exception quando deve - caso simples.
 *//*from   www  . j a  v a2 s .c  o  m*/
@Test
public void testParseValidatComErro() throws Exception {
    String sXML = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n" + "<raiz><filho/></raiz>";

    try {
        MParser.parse(new ByteArrayInputStream(sXML.getBytes()), true, true);
        fail("Deveria ter ocorrido um erro no parse");
    } catch (SAXException e) {
        if (!e.getMessage().startsWith("Erro(s) efetuando")) {
            throw e;
        }
        //ok - chegou o erro esperado
    }
}

From source file:org.opensingular.internal.lib.commons.xml.TestMElement.java

License:asdf

/**
 * Verifica se o parse dispara exception quando o XML no obdece ao DTD.
 *//*from www  .j a v a  2s  .c  om*/
@Test
public void testParseValidatDTDNaoSatisfeito() throws Exception {
    String sXML = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
            + "<!DOCTYPE raiz SYSTEM \"http://eee/teste-dtd-existe.dtd\">\n" + "<raiz><filho3/></raiz>";
    String sDTD = "<!ELEMENT raiz (filho, filho2?)>\n" + "<!ELEMENT filho (#PCDATA)>\n"
            + "<!ELEMENT filho2 (#PCDATA)>\n";

    MParser p = new MParser();
    p.addInputSource("http://eee/teste-dtd-existe.dtd", sDTD);
    try {
        p.parseComResolver(new ByteArrayInputStream(sXML.getBytes()));
        fail("Deveria ter ocorrido um erro no parse");
    } catch (SAXException e) {
        if (e.getMessage().indexOf("does not allow \"filho3\"") == -1
                && e.getMessage().indexOf("\"filho3\" must be declared") == -1) {
            throw e;
        }
        //ok - chegou o erro esperado
    }
}

From source file:org.osaf.cosmo.cmp.CmpServlet.java

private void processSignup(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    if (disableSignups) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
    } else {//from   w w  w  . ja v  a2 s  .  c  om
        try {
            Document xmldoc = readXmlRequest(req);
            UserResource resource = new UserResource(getUrlBase(req), xmldoc, entityFactory);
            User user = resource.getUser();
            user.setAdmin(Boolean.FALSE);
            user.setLocked(Boolean.FALSE);
            user = userService.createUser(user, createSignupListeners(req));

            resource = new UserResource(user, getUrlBase(req));
            resp.setStatus(HttpServletResponse.SC_CREATED);
            resp.setHeader("Content-Location", resource.getHomedirUrl());
            resp.setHeader("ETag", resource.getEntityTag());
            sendXmlResponse(resp, resource);
        } catch (SAXException e) {
            log.warn("error parsing request body: " + e.getMessage());
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Error parsing request body: " + e.getMessage());
            return;
        } catch (CmpException e) {
            log.warn("bad request for signup: " + e.getMessage());
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        } catch (ModelValidationException e) {
            handleModelValidationError(resp, e);
        } catch (InvalidStateException ise) {
            handleInvalidStateException(resp, ise);
        }
    }
}

From source file:org.osaf.cosmo.cmp.CmpServlet.java

private void processAccountUpdate(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    try {//w w w .  ja v  a 2s .  c om
        Document xmldoc = readXmlRequest(req);
        String urlUsername = usernameFromPathInfo(req.getPathInfo());
        User user = getLoggedInUser();
        String oldUsername = user.getUsername();
        Boolean oldAdmin = user.getAdmin();
        Boolean oldLocked = user.isLocked();
        UserResource resource = new UserResource(user, getUrlBase(req), xmldoc, entityFactory);
        if (user.isUsernameChanged()) {
            // reset logged in user's username
            user.setUsername(oldUsername);
            log.warn("bad request for account update: " + "username may not be changed");
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Username may not be changed");
            return;
        }
        if (user.isAdminChanged() && !oldAdmin) {
            // Non admin tried to change admin status
            user.setAdmin(oldAdmin);
            log.warn("bad request for account update: " + "non-admin may not change own admin status");
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Non admin may not change own admin status.");
            return;

        }
        if (user.isLocked() != oldLocked) {
            user.setLocked(oldLocked);
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "User may not changed own locked status.");
        }
        userService.updateUser(user);
        resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        resp.setHeader("ETag", resource.getEntityTag());
    } catch (SAXException e) {
        log.warn("error parsing request body: " + e.getMessage());
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Error parsing request body: " + e.getMessage());
        return;
    } catch (CmpException e) {
        log.warn("bad request for account update: " + e.getMessage());
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    } catch (ModelValidationException e) {
        handleModelValidationError(resp, e);
    } catch (InvalidStateException ise) {
        handleInvalidStateException(resp, ise);
    }
}

From source file:org.osaf.cosmo.cmp.CmpServlet.java

private void processUserCreate(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    try {// w w w.ja va  2s  . co  m
        Document xmldoc = readXmlRequest(req);
        String urlUsername = usernameFromPathInfo(req.getPathInfo());
        UserResource resource = new UserResource(getUrlBase(req), xmldoc, entityFactory);
        User user = resource.getUser();
        if (user.getUsername() != null && !user.getUsername().equals(urlUsername)) {
            log.warn("bad request for user create: " + "username does not match request URI");
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Username does not match request URI");
            return;
        }

        user = userService.createUser(user, createUserCreateListeners(req));

        resp.setStatus(HttpServletResponse.SC_CREATED);
        resp.setHeader("ETag", resource.getEntityTag());
    } catch (SAXException e) {
        log.warn("error parsing request body: " + e.getMessage());
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Error parsing request body: " + e.getMessage());
        return;
    } catch (CmpException e) {
        log.warn("bad request for user create: " + e.getMessage());
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    } catch (ModelValidationException e) {
        handleModelValidationError(resp, e);
    } catch (InvalidStateException ise) {
        handleInvalidStateException(resp, ise);
    }
}