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:com.ibm.dbwkl.request.internal.LoggingHandler.java

/**
 * @return xml output/*from w  w  w . j  a va2 s .  c  om*/
 */
@Override
public Document getXML() {
    if (hasRequestOption(Options.LOG_LIST)) {
        try {
            List<LoggerEntry> logEntries = Logger.getLogEntries();

            int entriesToShow = Integer.parseInt(getRequestOption(Options.LOG_LIST));

            if (entriesToShow < logEntries.size())
                logEntries = logEntries.subList(logEntries.size() - entriesToShow, logEntries.size());
            // create the document
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.newDocument();

            // create the document root node
            Element root = document.createElement("db2wklresult");
            document.appendChild(root);

            // create the result information
            Element rc = document.createElement("rc");
            rc.setTextContent(Integer.toString(this.getResult().rc));
            root.appendChild(rc);

            Element object = document.createElement("resultObject");
            object.setTextContent(
                    this.getResult().resultObj == null ? "" : this.getResult().resultObj.toString());

            Element entries = null;

            for (LoggerEntry logEntry : logEntries) {
                entries = document.createElement("logEntry");
                entries.setAttribute("formattedTime", logEntry.getFormatedTime());
                entries.setAttribute("requestName", logEntry.getRequestName());
                entries.setAttribute("loglevel", logEntry.getLevel());
                entries.setAttribute("message", logEntry.getMessage().replaceAll(String.valueOf('"'), "'"));
                entries.setAttribute("class", logEntry.getClasse());
                entries.setAttribute("method", logEntry.getMethod());
                entries.setAttribute("line", String.valueOf(logEntry.getLineNumber()));
                entries.setAttribute("thread", logEntry.getThread());
                entries.setAttribute("threadGroup", logEntry.getThreadGroup());
                object.appendChild(entries);
            }

            root.appendChild(object);

            // return the resulting document
            return document;
        } catch (ParserConfigurationException e) {
            Logger.log(e.getMessage(), LogLevel.Error);
        }
    }

    return null;
}

From source file:com.qcadoo.view.internal.xml.ViewDefinitionParserImpl.java

@Override
public ViewExtension getViewExtensionNode(final InputStream resource, final String tagType)
        throws ViewDefinitionParserNodeException {
    try {//ww  w.  j  a v a  2s.co m
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = documentBuilder.parse(resource);

        Node root = document.getDocumentElement();

        checkState(root.getNodeName().equals(tagType), root,
                "Wrong root node name '" + root.getNodeName() + "'");

        String plugin = getStringAttribute(root, "plugin");
        String view = getStringAttribute(root, "view");

        checkState(plugin != null, root, "View extension error: plugin not defined");
        checkState(view != null, root, "View extension error: view not defined");

        return new ViewExtension(plugin, view, root);

    } catch (ParserConfigurationException e) {
        throw new IllegalStateException(e.getMessage(), e);
    } catch (SAXException e) {
        throw new IllegalStateException(e.getMessage(), e);
    } catch (IOException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}

From source file:com.centeractive.ws.builder.soap.XmlUtils.java

private static DocumentBuilder ensureDocumentBuilder() {
    if (documentBuilder == null) {
        try {/*from  ww w .  j a  v a  2  s  .c  om*/
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            documentBuilder = dbf.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            log.error("Error creating DocumentBuilder; " + e.getMessage());
        }
    }

    return documentBuilder;
}

From source file:com.urbancode.terraform.main.Main.java

/**
 * Initializes Terraform so it can execute the given commands.
 * Here is the order of operations://from w ww . jav a2s. co  m
 * Parses the credentials file and verifies the given credentials.
 * Generates a random string for this environment, which is appended to the output xml file.
 * Parses the xml file.
 * Runs the specified command (create, destroy, etc).
 * @throws XmlParsingException
 * @throws IOException
 * @throws CredentialsException
 * @throws CreationException
 * @throws DestructionException
 * @throws RestorationException
 */
public void execute() throws XmlParsingException, IOException, CredentialsException, CreationException,
        DestructionException, RestorationException {
    TerraformContext context = null;
    try {
        // parse xml and set context
        context = parseContext(inputXmlFile);

        Credentials credentials = parseCredentials(credsFile);

        context.setCredentials(credentials);
        if (AllowedCommands.CREATE.getCommandName().equalsIgnoreCase(command)) {
            // create new file if creating a new environment
            UUID uuid = UUID.randomUUID();
            //convert uuid to base 62 (allowed chars: 0-9 a-z A-Z)
            ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
            bb.putLong(uuid.getMostSignificantBits());
            bb.putLong(uuid.getLeastSignificantBits());
            String suffix = Base64.encodeBase64URLSafeString(bb.array());
            suffix = suffix.replaceAll("-", "Y");
            suffix = suffix.replaceAll("_", "Z");
            suffix = suffix.substring(0, 4);
            if (context.getEnvironment() != null) {
                context.getEnvironment().addSuffixToEnvName(suffix);
                log.debug("UUID for env " + context.getEnvironment().getName() + " is " + suffix);
            } else {
                throw new NullPointerException("No environment on context!");
            }

            String name = context.getEnvironment().getName();
            log.debug("Output filename = " + name);
            outputXmlFile = new File("env-" + name + ".xml");

            log.debug("Calling create() on context");
            context.create();
        } else if (AllowedCommands.DESTROY.getCommandName().equalsIgnoreCase(command)) {
            String suffix = parseSuffix(context.getEnvironment().getName());
            context.getEnvironment().setSuffix(suffix);
            log.debug("found suffix " + suffix);
            // write out instance failure regardless of success or failure
            outputXmlFile = inputXmlFile;
            log.debug("Calling destroy() on context");
            context.destroy();
        } else if (AllowedCommands.SUSPEND.getCommandName().equalsIgnoreCase(command)) {
            outputXmlFile = inputXmlFile;
            log.debug("Calling restore() on context");
            log.info("Attempting to suspend power on all instances/VMs in the environment.");
            context.restore();
            if (context instanceof ContextVmware) {
                SuspendCommand newCommand = new SuspendCommand((ContextVmware) context);
                newCommand.execute();
            } else if (context instanceof ContextAWS) {
                com.urbancode.terraform.commands.aws.SuspendCommand newCommand = new com.urbancode.terraform.commands.aws.SuspendCommand(
                        (ContextAWS) context);
                newCommand.execute();
            } else {
                log.warn("Could not resolve context to call command \"" + command + "\"");
            }
        } else if (AllowedCommands.RESUME.getCommandName().equalsIgnoreCase(command)) {
            outputXmlFile = inputXmlFile;
            log.debug("Calling restore() on context");
            context.restore();
            log.info("Attempting to power on all instances/VMs in the environment.");
            if (context instanceof ContextVmware) {
                ResumeCommand newCommand = new ResumeCommand((ContextVmware) context);
                newCommand.execute();
            } else if (context instanceof ContextAWS) {
                com.urbancode.terraform.commands.aws.ResumeCommand newCommand = new com.urbancode.terraform.commands.aws.ResumeCommand(
                        (ContextAWS) context);
                newCommand.execute();
            }

            else {
                log.warn("Could not resolve context to call command \"" + command + "\"");
            }
        } else if (AllowedCommands.TAKE_SNAPSHOT.getCommandName().equalsIgnoreCase(command)) {
            outputXmlFile = inputXmlFile;
            log.debug("Calling restore() on context");
            context.restore();
            log.info("Attempting to take snapshots of all instances/VMs in the environment.");
            if (context instanceof ContextVmware) {
                TakeSnapshotCommand newCommand = new TakeSnapshotCommand((ContextVmware) context);
                newCommand.execute();
            } else if (context instanceof ContextAWS) {
                log.warn("Taking snapshots is not currently supported with Terraform and AWS.");
            }

            else {
                log.warn("Could not resolve context to call command \"" + command + "\"");
            }
        }
    } catch (ParserConfigurationException e1) {
        throw new XmlParsingException("ParserConfigurationException: " + e1.getMessage(), e1);
    } catch (SAXException e2) {
        throw new XmlParsingException("SAXException: " + e2.getMessage(), e2);
    } finally {
        if (context != null && context.doWriteContext() && outputXmlFile != null) {
            log.debug("Writing context out to " + outputXmlFile);
            writeEnvToXml(outputXmlFile, context);
        }
    }
}

From source file:com.evolveum.midpoint.pwdfilter.opendj.PasswordPusher.java

private void processFile(File file) {

    try {/*from  w  ww.  ja  v  a 2s .  c o m*/
        FileInputStream fis = new FileInputStream(file);

        String s = IOUtils.toString(fis, "UTF-8").trim();
        System.out.println(s);

        String[] a = file.getName().split("_");
        cipherUtils.setEncryptionKeyAlias(a[0]);

        String xml = cipherUtils.decrypt(s);

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        Document doc = db.parse(new InputSource(new StringReader(xml)));

        String dn = doc.getElementsByTagName("userDN").item(0).getTextContent();
        String password = doc.getElementsByTagName("newPassword").item(0).getTextContent();

        fis.close();

        if (updatePassword(dn, password)) {
            file.delete();
        } else {
            // Record error
            System.out.println("Error updating password for " + dn); // TODO handle better
        }
    } catch (IOException ioe) {
        System.out.println("Error reading encrypted password change back from " + file.getName() + ", "
                + ioe.getMessage()); // TODO handle better
    } catch (ParserConfigurationException pce) {
        System.out.println("Error parsing XML document of password change back from " + file.getName() + ", "
                + pce.getMessage()); // TODO handle better
    } catch (SAXException se) {
        System.out.println("Error parsing XML document of password change back from " + file.getName() + ", "
                + se.getMessage()); // TODO handle better
    }
}

From source file:com.waitwha.nessus.server.Server.java

/**
 * Constructor/*from  w  ww .j av  a 2s  . co m*/
 *
 * @param url   End-point URL of the Nessus Server. (i.e. https://localhost:8834)
 */
public Server(final String url) {
    this.url = url;

    /*
     * Configure XML parsing.
     */
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
        this.builder = factory.newDocumentBuilder();
        log.finest(String.format("Successfully configured XML parsing using builder: %s",
                this.builder.getClass().getName()));

    } catch (ParserConfigurationException e) {
        log.warning(String.format("Could not configure XML parsing: %s", e.getMessage()));

    }

    /*
     * Setup SSL for HttpClient configurations. Here we will configure SSL/TLS to 
     * accept all hosts (no verification on certificates). This is because Nessus by
     * default used a self-generate CA and certificate for the servers. So, a simple 
     * self-signed-strategy will not work as we are not dealing with strictly 
     * self-signed certs, but ones generated and signed by a self-generated CA. 
     * 
     * TODO Perhaps the serial number of the CA is always the same so in the future we
     * could use a strategy to only accept certs by this one serial.
     * 
     * See http://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientConfiguration.java.
     * 
     * TODO We need to work on the code here to be more up-to-date. SSLSocketFactory is deprecated, but 
     * finding up-to-date docs on how to use SSLContext with a custom TrustStrategy and not using a KeyStore is
     * not currently available.
     */
    //SSLContext sslContext = SSLContexts.createSystemDefault();
    Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
    try {
        socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", new SSLSocketFactory(new MyTrustStrategy(),
                        SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER))
                .build();
        log.finest(String.format("Configured SSL/TLS connections for %s.", url));

    } catch (Exception e) {
        log.warning(
                String.format("Could not configure SSL/TLS: %s %s", e.getClass().getName(), e.getMessage()));

    }

    SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
    this.connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry);
    this.connectionManager.setSocketConfig(socketConfig);
    log.finest(String.format("Configured socket connections for %s.", url));

    this.cookieStore = new BasicCookieStore() {

        private static final long serialVersionUID = 1L;

        /**
         * @see org.apache.http.impl.client.BasicCookieStore#addCookie(org.apache.http.cookie.Cookie)
         */
        @Override
        public synchronized void addCookie(Cookie cookie) {
            log.finest(String.format("[%s] Cookie added: %s=%s", url, cookie.getName(), cookie.getValue()));
            super.addCookie(cookie);
        }

    };
    log.finest(String.format("Configured default/basic cookie storage for connections to %s", url));

}

From source file:com.wwpass.connection.WWPassConnection.java

private static InputStream getReplyData(final InputStream rawXMLInput)
        throws IOException, WWPassProtocolException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document dom;// w w  w  . java 2 s . c  om
    InputStream is = null;

    try {
        DocumentBuilder db = dbf.newDocumentBuilder();

        is = rawXMLInput;

        dom = db.parse(is);

        Element docEle = dom.getDocumentElement();

        Node result = docEle.getElementsByTagName("result").item(0);
        boolean res = result.getTextContent().equalsIgnoreCase("true");

        Element data = (Element) docEle.getElementsByTagName("data").item(0);
        String encoding = data.getAttributes().getNamedItem("encoding").getTextContent();
        String strData;
        byte[] bb;
        if ("base64".equalsIgnoreCase(encoding)) {
            bb = (new Base64()).decode(data.getTextContent());
            strData = new String(bb, Charset.forName("UTF-8"));
            if (!res) {
                throw new WWPassProtocolException("SPFE returned error: " + strData);
            }
            return new ByteArrayInputStream(bb);
        } else {
            strData = data.getTextContent();
            if (!res) {
                throw new WWPassProtocolException("SPFE returned error: " + strData);
            }
            return new ByteArrayInputStream(strData.getBytes());
        }

    } catch (ParserConfigurationException pce) {
        throw new WWPassProtocolException("Malformed SPFE reply: " + pce.getMessage());
    } catch (SAXException se) {
        throw new WWPassProtocolException("Malformed SPFE reply: " + se.getMessage());
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:net.sbbi.upnp.messages.StateVariableMessage.java

/**
 * Executes the state variable query and retuns the UPNP device response, according to the UPNP specs,
 * this method could take up to 30 secs to process ( time allowed for a device to respond to a request )
 * @return a state variable response object containing the variable value
 * @throws IOException if some IOException occurs during message send and reception process
 * @throws UPNPResponseException if an UPNP error message is returned from the server
 *         or if some parsing exception occurs ( detailErrorCode = 899, detailErrorDescription = SAXException message )
 *//*from   w ww. ja  v a 2  s.c  om*/
public StateVariableResponse service() throws IOException, UPNPResponseException {
    StateVariableResponse rtrVal = null;
    UPNPResponseException upnpEx = null;
    IOException ioEx = null;
    StringBuffer body = new StringBuffer(256);

    body.append("<?xml version=\"1.0\"?>\r\n");
    body.append("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"");
    body.append(" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">");
    body.append("<s:Body>");
    body.append("<u:QueryStateVariable xmlns:u=\"urn:schemas-upnp-org:control-1-0\">");
    body.append("<u:varName>").append(serviceStateVar.getName()).append("</u:varName>");
    body.append("</u:QueryStateVariable>");
    body.append("</s:Body>");
    body.append("</s:Envelope>");

    if (log.isDebugEnabled())
        log.debug("POST prepared for URL " + service.getControlURL());
    URL url = new URL(service.getControlURL().toString());
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    HttpURLConnection.setFollowRedirects(false);
    //conn.setConnectTimeout( 30000 );
    conn.setRequestProperty("HOST", url.getHost() + ":" + url.getPort());
    conn.setRequestProperty("SOAPACTION", "\"urn:schemas-upnp-org:control-1-0#QueryStateVariable\"");
    conn.setRequestProperty("CONTENT-TYPE", "text/xml; charset=\"utf-8\"");
    conn.setRequestProperty("CONTENT-LENGTH", Integer.toString(body.length()));
    OutputStream out = conn.getOutputStream();
    out.write(body.toString().getBytes());
    out.flush();
    conn.connect();
    InputStream input = null;

    if (log.isDebugEnabled())
        log.debug("executing query :\n" + body);
    try {
        input = conn.getInputStream();
    } catch (IOException ex) {
        // java can throw an exception if he error code is 500 or 404 or something else than 200
        // but the device sends 500 error message with content that is required
        // this content is accessible with the getErrorStream
        input = conn.getErrorStream();
    }

    if (input != null) {
        int response = conn.getResponseCode();
        String responseBody = getResponseBody(input);
        if (log.isDebugEnabled())
            log.debug("received response :\n" + responseBody);
        SAXParserFactory saxParFact = SAXParserFactory.newInstance();
        saxParFact.setValidating(false);
        saxParFact.setNamespaceAware(true);
        StateVariableResponseParser msgParser = new StateVariableResponseParser(serviceStateVar);
        StringReader stringReader = new StringReader(responseBody);
        InputSource src = new InputSource(stringReader);
        try {
            SAXParser parser = saxParFact.newSAXParser();
            parser.parse(src, msgParser);
        } catch (ParserConfigurationException confEx) {
            // should never happen
            // we throw a runtimeException to notify the env problem
            throw new RuntimeException(
                    "ParserConfigurationException during SAX parser creation, please check your env settings:"
                            + confEx.getMessage());
        } catch (SAXException saxEx) {
            // kind of tricky but better than nothing..
            upnpEx = new UPNPResponseException(899, saxEx.getMessage());
        } finally {
            try {
                input.close();
            } catch (IOException ex) {
                // ignoring
            }
        }
        if (upnpEx == null) {
            if (response == HttpURLConnection.HTTP_OK) {
                rtrVal = msgParser.getStateVariableResponse();
            } else if (response == HttpURLConnection.HTTP_INTERNAL_ERROR) {
                upnpEx = msgParser.getUPNPResponseException();
            } else {
                ioEx = new IOException("Unexpected server HTTP response:" + response);
            }
        }
    }
    try {
        out.close();
    } catch (IOException ex) {
        // ignore
    }
    conn.disconnect();
    if (upnpEx != null) {
        throw upnpEx;
    }
    if (rtrVal == null && ioEx == null) {
        ioEx = new IOException("Unable to receive a response from the UPNP device");
    }
    if (ioEx != null) {
        throw ioEx;
    }
    return rtrVal;
}

From source file:org.openhab.habdroid.ui.OpenHABRoomSettingActivity.java

private List<OpenHABSitemap> parseSitemapList(String xmlContent) {
    List<OpenHABSitemap> sitemapList = new ArrayList<OpenHABSitemap>();
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;/*from   ww w  . j av  a 2  s . c om*/
    try {
        builder = factory.newDocumentBuilder();
        Document document;
        document = builder.parse(new ByteArrayInputStream(xmlContent.getBytes("UTF-8")));
        NodeList sitemapNodes = document.getElementsByTagName("sitemap");
        if (sitemapNodes.getLength() > 0) {
            for (int i = 0; i < sitemapNodes.getLength(); i++) {
                Node sitemapNode = sitemapNodes.item(i);
                OpenHABSitemap openhabSitemap = new OpenHABSitemap(sitemapNode);
                sitemapList.add(openhabSitemap);
            }
        }
    } catch (ParserConfigurationException e) {
        Log.e(TAG, e.getMessage());
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, e.getMessage());
    } catch (SAXException e) {
        Log.e(TAG, e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
    }
    return sitemapList;
}

From source file:com.sshtools.common.hosts.AbstractHostKeyVerification.java

/**
 * Creates a new AbstractHostKeyVerification object.
 *
 * @param hostFileName/*ww w  .  j  a v  a 2  s .  c o  m*/
 *
 * @throws InvalidHostFileException
 */
public AbstractHostKeyVerification(String hostFileName) throws InvalidHostFileException {
    InputStream in = null;

    try {
        //  If no host file is supplied, or there is not enough permission to load
        //  the file, then just create an empty list.
        if (hostFileName != null) {
            if (System.getSecurityManager() != null) {
                AccessController.checkPermission(new FilePermission(hostFileName, "read"));
            }

            //  Load the hosts file. Do not worry if fle doesnt exist, just disable
            //  save of
            File f = new File(hostFileName);

            if (f.exists()) {
                in = new FileInputStream(f);
                hostFile = hostFileName;

                SAXParserFactory saxFactory = SAXParserFactory.newInstance();
                SAXParser saxParser = saxFactory.newSAXParser();
                saxParser.parse(in, this);
                hostFileWriteable = f.canWrite();
            } else {
                // Try to create the file
                if (f.createNewFile()) {
                    FileOutputStream out = new FileOutputStream(f);
                    out.write(toString().getBytes());
                    out.close();
                    hostFileWriteable = true;
                } else {
                    hostFileWriteable = false;
                }
            }

            if (!hostFileWriteable) {
                log.warn("Host file is not writeable.");
            }
        }
    } catch (AccessControlException ace) {
        log.warn("Not enough permission to load a hosts file, so just creating an empty list");
    } catch (IOException ioe) {
        throw new InvalidHostFileException("Could not open or read " + hostFileName);
    } catch (SAXException sax) {
        throw new InvalidHostFileException("Failed XML parsing: " + sax.getMessage());
    } catch (ParserConfigurationException pce) {
        throw new InvalidHostFileException("Failed to initialize xml parser: " + pce.getMessage());
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ioe) {
            }
        }
    }
}