Example usage for javax.xml.parsers ParserConfigurationException getMessage

List of usage examples for javax.xml.parsers ParserConfigurationException getMessage

Introduction

In this page you can find the example usage for javax.xml.parsers ParserConfigurationException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

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

/**
 * Adds the the dictionary found in <code>file</code> to the current i18n
 * definitions./* w w w .jav a 2s .  com*/
 * 
 * @param url
 *          the i18n dictionary
 * @param language
 *          the dictionary language
 */
public void addDictionary(URL url, Language language) {
    DocumentBuilder docBuilder;
    try {
        docBuilder = XMLUtils.getDocumentBuilder();
        Document doc = docBuilder.parse(url.openStream());

        if (language != null)
            logger.debug("Reading i18n dictionary {} ({})", url.getFile(), language);
        else
            logger.debug("Reading default i18n dictionary {}", url.getFile());

        // Get the target properties

        Properties p = null;
        if (language != null) {
            p = i18n.get(language);
            if (p == null) {
                p = new Properties();
                i18n.put(language, p);
            }
        } else {
            p = defaults;
        }

        int invalidKeys = 0;
        int invalidValues = 0;

        // Read and store the messages

        XPath path = XMLUtils.getXPath();
        NodeList nodes = XPathHelper.selectList(doc, "/resources/string", path);
        for (int j = 0; j < nodes.getLength(); j++) {
            Node messageNode = nodes.item(j);
            String key = XPathHelper.valueOf(messageNode, "@name", path);
            String value = XPathHelper.valueOf(messageNode, "text()", path);
            if (key == null) {
                invalidKeys++;
                continue;
            }
            if (value == null) {
                logger.debug("I18n dictionary {} lacks a value for key '{}'", url, key);
                invalidValues++;
                continue;
            }
            if (p.containsKey(key)) {
                logger.warn("I18n key '{}' redefined in {}", key, url);
            }
            p.put(key, value);
        }

        if (invalidKeys > 0)
            logger.warn("I18n dictionary {} contains {} entries withou a key", url, invalidKeys);
        if (invalidValues > 0)
            logger.warn("I18n dictionary {} contains {} keys without values", url, invalidValues);

    } catch (ParserConfigurationException e) {
        logger.warn("Parser configuration error when reading i18n dictionary {}: {}", url, e.getMessage());
    } catch (SAXException e) {
        logger.warn("SAX exception while parsing i18n dictionary {}: {}", url, e.getMessage());
    } catch (IOException e) {
        logger.warn("IO exception while parsing i18n dictionary {}: {}", url, e.getMessage());
    }
}

From source file:com.freedomotic.plugins.devices.ipx800.Ipx800.java

private Document getXMLStatusFile(Board board) {
    final Board b = board;
    //get the xml file from the socket connection
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = null;
    try {/*from  w  w  w.  java 2 s .  c  om*/
        dBuilder = dbFactory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        LOG.error(ex.getMessage());
    }
    Document doc = null;
    String statusFileURL = null;
    try {
        if (board.getAuthentication().equalsIgnoreCase("true")) {
            Authenticator.setDefault(new Authenticator() {

                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(b.getUsername(), b.getPassword().toCharArray());
                }
            });
            statusFileURL = "http://" + b.getIpAddress() + ":" + Integer.toString(b.getPort())
                    + b.getPathAuthentication() + "/" + GET_STATUS_URL;
        } else {
            statusFileURL = "http://" + board.getIpAddress() + ":" + Integer.toString(board.getPort()) + "/"
                    + GET_STATUS_URL;
        }
        LOG.info("Ipx800 gets relay status from file {0}", statusFileURL);
        doc = dBuilder.parse(new URL(statusFileURL).openStream());
        doc.getDocumentElement().normalize();
    } catch (ConnectException connEx) {
        LOG.error(Freedomotic.getStackTraceInfo(connEx));
        //disconnect();
        this.stop();
        this.setDescription("Connection timed out, no reply from the board at " + statusFileURL);
    } catch (SAXException ex) {
        //this.stop();
        LOG.error(Freedomotic.getStackTraceInfo(ex));
    } catch (Exception ex) {
        //this.stop();
        setDescription("Unable to connect to " + statusFileURL);
        LOG.error(Freedomotic.getStackTraceInfo(ex));
    }
    return doc;
}

From source file:ca.uhn.hunit.event.expect.AbstractXmlExpectMessage.java

@Override
public void receiveMessage(IExecutionContext theCtx, TestMessage<?> theMessage) throws TestFailureException {
    Document parsedMessage = (Document) theMessage.getParsedMessage();

    if (parsedMessage == null) {
        final String rawMessage = theMessage.getRawMessage();

        try {/*from  ww  w  .  j  ava2  s  .c  o m*/
            DocumentBuilder parser = myParserFactory.newDocumentBuilder();
            parser.setErrorHandler(new MyErrorHandler(LogFactory.INSTANCE.get(getTest())));
            parsedMessage = parser.parse(new InputSource(new StringReader(rawMessage)));
        } catch (ParserConfigurationException ex) {
            throw new UnexpectedTestFailureException("Unable to set up XML parser", ex);
        } catch (SAXException ex) {
            throw new IncorrectMessageReceivedException(getTest(), theMessage,
                    "Unable to parse incoming message: " + ex.getMessage());
        } catch (IOException ex) {
            throw new UnexpectedTestFailureException(ex);
        }

        TestMessage<Document> testMessage = new TestMessage<Document>(rawMessage, parsedMessage);
        validateMessage(testMessage);
    }
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

public static DocumentBuilder createDocumentBuilder() {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//from www.j  a va  2  s. com
    try {
        return factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new IllegalStateException("Error creating document builder " + e.getMessage(), e);
    }
}

From source file:com.twinsoft.convertigo.engine.util.RemoteAdmin.java

private void decodeResponseError(String httpResponse) throws RemoteAdminException {
    Document domResponse;/*ww w  . j av a2s. c  om*/
    try {
        DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        domResponse = parser.parse(new InputSource(new StringReader(httpResponse)));
        domResponse.normalize();

        NodeList nodeList = domResponse.getElementsByTagName("error");

        if (nodeList.getLength() != 0) {
            Element errorNode = (Element) nodeList.item(0);

            Element errorMessage = (Element) errorNode.getElementsByTagName("message").item(0);

            Element exceptionName = (Element) errorNode.getElementsByTagName("exception").item(0);

            Element stackTrace = (Element) errorNode.getElementsByTagName("stacktrace").item(0);

            throw new RemoteAdminException(errorMessage.getTextContent(),
                    exceptionName == null ? "" : exceptionName.getTextContent(),
                    stackTrace == null ? "" : stackTrace.getTextContent());
        }
    } catch (ParserConfigurationException e) {
        throw new RemoteAdminException("Unable to parse the Convertigo server response: \n" + e.getMessage()
                + ".\n" + "Received response: " + httpResponse);
    } catch (IOException e) {
        throw new RemoteAdminException(
                "An unexpected error has occured during the Convertigo project deployment.\n" + "(IOException) "
                        + e.getMessage() + "\n" + "Received response: " + httpResponse,
                e);
    } catch (SAXException e) {
        throw new RemoteAdminException("Unable to parse the Convertigo server response: " + e.getMessage()
                + ".\n" + "Received response: " + httpResponse);
    }
}

From source file:org.openhab.binding.rwesmarthome.internal.communicator.RWESmarthomeSession.java

/**
 * Logon and initialize a session./*w ww  .  j  a  v  a  2s.co m*/
 * 
 * @param username
 *            the user name
 * @param password
 *            the pass word
 * @param hostname
 *            the host name
 * @throws SHTechnicalException
 *             the sH technical exception
 * @throws LoginFailedException
 *             the login failed exception
 */
public void logon(String username, String password, String hostname)
        throws SHTechnicalException, LoginFailedException {
    this.hostname = hostname;

    clientId = UUID.randomUUID().toString();
    requestId = generateRequestId();
    passwordEncrypted = generateHashFromPassword(password);
    final String LOGIN_REQUEST = String.format(
            "<BaseRequest xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"LoginRequest\" Version=\"%s\" RequestId=\"%s\" UserName=\"%s\" Password=\"%s\" />",
            FIRMWARE_VERSION, requestId, username, passwordEncrypted);
    String sResponse = "";

    try {

        sResponse = executeRequest(LOGIN_REQUEST, "/cmd", true);
        sessionId = XMLUtil.XPathValueFromString(sResponse, "/BaseResponse/@SessionId");
        if (sessionId == null || "".equals(sessionId)) {
            throw new LoginFailedException(String.format(
                    "LoginFailed: Authentication with user '%s' was not possible. Session ID is empty.",
                    username));
        }
        currentConfigurationVersion = XMLUtil.XPathValueFromString(sResponse,
                "/BaseResponse/@CurrentConfigurationVersion");
    } catch (ParserConfigurationException ex) {
        throw new SHTechnicalException("ParserConfigurationException:" + ex.getMessage(), ex);
    } catch (SAXException ex) {
        throw new SHTechnicalException("SAXException:" + ex.getMessage(), ex);
    } catch (XPathExpressionException ex) {
        throw new SHTechnicalException("XPathExpressionException:" + ex.getMessage(), ex);
    } catch (IOException ex) {
        throw new SHTechnicalException(
                String.format("IOException. Communication with host '%s' was not possible or interrupted: %s",
                        hostname, ex.getMessage()),
                ex);
    } catch (RWESmarthomeSessionExpiredException e) {
        logger.error("SessionExpiredException while login?!? Should never exist...");
        throw new SHTechnicalException("SessionExpiredException while login?!? Should never exist...");
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.web.templatemodels.customlistview.CustomListViewConfigFile.java

private Document parseDocument(Reader reader) throws InvalidConfigurationException {
    if (reader == null) {
        throw new InvalidConfigurationException("Config file reader is null.");
    }// w w w.  jav a 2  s.  c o  m

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new InputSource(reader));
        return doc;
    } catch (ParserConfigurationException e) {
        throw new InvalidConfigurationException("Problem with XML parser.", e);
    } catch (SAXException e) {
        throw new InvalidConfigurationException("Config file is not valid XML: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new InvalidConfigurationException("Unable to read config file.", e);
    }
}

From source file:com.jaspersoft.jasperserver.rest.services.RESTResource.java

/**
 * POST can be used to modify a resource or to copy/move it.
 *
 * @param req//ww  w . j av  a 2  s . co  m
 * @param resp
 * @throws ServiceException
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    String sourceURI = restUtils.extractRepositoryUri(req.getPathInfo());
    String destURI = restUtils.getDetinationUri(req);
    if (destURI != null) {
        if (req.getParameterMap().containsKey(restUtils.REQUEST_PARAMENTER_COPY_TO))
            resourcesManagementRemoteService.copyResource(sourceURI, destURI);
        else
            resourcesManagementRemoteService.moveResource(sourceURI, destURI);
    } else // Modify the resource...
    {
        HttpServletRequest mreq = restUtils.extractAttachments(runReportService, req);
        String resourceDescriptorXml = null;

        // get the resource descriptor...
        if (mreq instanceof MultipartHttpServletRequest)
            resourceDescriptorXml = mreq.getParameter(restUtils.REQUEST_PARAMENTER_RD);
        else {
            try {
                resourceDescriptorXml = IOUtils.toString(req.getInputStream());
            } catch (IOException ex) {
                throw new ServiceException(ServiceException.INTERNAL_SERVER_ERROR, ex.getLocalizedMessage());
            }
        }
        if (resourceDescriptorXml == null) {
            String msg = "Missing parameter " + restUtils.REQUEST_PARAMENTER_RD + " "
                    + runReportService.getInputAttachments();
            restUtils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, msg);
            throw new ServiceException(ServiceException.INTERNAL_SERVER_ERROR, msg);
        }

        // Parse the resource descriptor...
        InputSource is = new InputSource(new StringReader(resourceDescriptorXml));
        Document doc = null;
        ResourceDescriptor rd = null;
        try {
            doc = XMLUtil.getNewDocumentBuilder().parse(is);
            rd = Unmarshaller.readResourceDescriptor(doc.getDocumentElement());

            // we force the rd to be new...
            rd.setIsNew(false);

            if (rd.getUriString() == null || !rd.getUriString().equals(sourceURI)) {
                throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST,
                        "Request URI and descriptor URI are not equals");
            }
            resourcesManagementRemoteService.updateResource(sourceURI, rd, true);

            restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, "");

        } catch (SAXException ex) {
            log.error("error parsing...", ex);
            throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
        } catch (ServiceException ex) {
            log.error("error executing the service...", ex);
            throw ex;
        } catch (ParserConfigurationException e) {
            throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        } catch (IOException e) {
            throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }
}

From source file:net.java.sen.StringTagger.java

/**
 * Read configuration file.//from w  w w .  java 2s .c o m
 * 
 * @param confFile
 *            configuration file
 */
private void readConfig(String confFile) {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        File cf = new File(confFile);
        String parent = cf.getParentFile().getParent();
        if (parent == null)
            parent = ".";
        Document doc = builder.parse(new InputSource(confFile));
        NodeList nl = doc.getFirstChild().getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            org.w3c.dom.Node n = nl.item(i);
            if (n.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
                String nn = n.getNodeName();
                String value = n.getFirstChild().getNodeValue();

                if (nn.equals("charset")) {
                    charset = value;
                } else if (nn.equals("unknown-pos")) {
                    unknownPos = value;
                } else if (nn.equals("tokenizer")) {
                    tokenizerClass = value;
                }

                if (nn.equals("dictionary")) {
                    // read nested tag in <dictinary>
                    NodeList dnl = n.getChildNodes();
                    for (int j = 0; j < dnl.getLength(); j++) {
                        org.w3c.dom.Node dn = dnl.item(j);
                        if (dn.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {

                            String dnn = dn.getNodeName();
                            if (dn.getFirstChild() == null) {
                                throw new IllegalArgumentException("element '" + dnn + "' is empty");
                            }
                            String dvalue = dn.getFirstChild().getNodeValue();

                            if (dnn.equals("connection-cost")) {
                                connectFile = SenUtils.getPath(dvalue, parent);
                            } else if (dnn.equals("double-array-trie")) {
                                doubleArrayFile = SenUtils.getPath(dvalue, parent);
                            } else if (dnn.equals("token")) {
                                tokenFile = SenUtils.getPath(dvalue, parent);
                            } else if (dnn.equals("pos-info")) {
                                posInfoFile = SenUtils.getPath(dvalue, parent);
                            } else if (dnn.equals("compound")) {
                                // do nothing
                            } else {
                                throw new IllegalArgumentException("element '" + dnn + "' is invalid");
                            }
                        }
                    }
                }
            }
        }
    } catch (ParserConfigurationException e) {
        throw new IllegalArgumentException(e.getMessage());
    } catch (FileNotFoundException e) {
        throw new IllegalArgumentException(e.getMessage());
    } catch (SAXException e) {
        throw new IllegalArgumentException(e.getMessage());
    } catch (IOException e) {
        throw new IllegalArgumentException(e.getMessage());
    }
}