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:edu.ucsd.xmlrpc.xmlrpc.server.XmlRpcStreamServer.java

protected XmlRpcRequest getRequest(final XmlRpcStreamRequestConfig pConfig, InputStream pStream)
        throws XmlRpcException {
    final XmlRpcRequestParser parser = new XmlRpcRequestParser(pConfig, getTypeFactory());
    final XMLReader xr = SAXParsers.newXMLReader();
    xr.setContentHandler(parser);/*  w w w.j a  va2  s  .  co m*/
    try {
        xr.parse(new InputSource(pStream));
    } catch (SAXException e) {
        Exception ex = e.getException();
        if (ex != null && ex instanceof XmlRpcException) {
            throw (XmlRpcException) ex;
        }
        throw new XmlRpcException("Failed to parse XML-RPC request: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new XmlRpcException("Failed to read XML-RPC request: " + e.getMessage(), e);
    }
    final List params = parser.getParams();
    // Ucsd modified code
    return new XmlRpcClientRequestImpl(pConfig, parser.getMethodName(), parser.getParams(), parser.getJobID());
    // end
}

From source file:act.installer.HMDBParser.java

/**
 * Extract all chemicals from HMDB XML files that live in the specified directory and save them in the DB.
 * Note that this search is not recursive: documents in sub-directories will be ignored.
 * @param inputDir The directory to scan for HMDB XML files.
 * @throws IOException/*from   w w w. j a v  a  2s . c  om*/
 * @throws IllegalArgumentException
 */
public void run(File inputDir) throws IOException, IllegalArgumentException {
    if (inputDir == null || !inputDir.isDirectory()) {
        String msg = String.format("Unable to read input directory at %s",
                inputDir == null ? "null" : inputDir.getAbsolutePath());
        LOGGER.error(msg);
        throw new RuntimeException(msg);
    }

    SortedSet<File> files = findHMDBFilesInDirectory(inputDir);
    LOGGER.info("Found %d HMDB XML files in directory %s", files.size(), inputDir.getAbsolutePath());

    for (File file : files) {
        LOGGER.debug("Processing HMDB XML file %s", file.getAbsolutePath());

        /* Promote our XML-specific exceptions to generic IllegalArgumentExceptions to reduce error handling surface
         * area for the caller. */
        Document d;
        try {
            d = documentBuilder.parse(file);
        } catch (SAXException e) {
            String msg = String.format("Unable to parse XML file at %s: %s", file.getAbsolutePath(),
                    e.getMessage());
            throw new IllegalArgumentException(msg, e);
        }

        /* Jaxen doesn't throw exceptions if it can't find a path, so a JaxenException here is completely unexpected.
         * It might mean corrupted XML or some unrecoverable XPath problem that we don't expect.  In any case, promote
         * the exception to the caller as it's unclear how we could deal with such an error here. */
        Chemical chem;
        try {
            chem = extractChemicalFromXMLDocument(d);
        } catch (JaxenException e) {
            String msg = String.format("Unable to extract features from XML file at %s: %s",
                    file.getAbsolutePath(), e.getMessage());
            throw new IllegalArgumentException(msg, e);
        }

        // Not all HMDB entries contain
        if (chem == null) {
            LOGGER.warn("Unable to create chemical from file %s", file.getAbsolutePath());
            continue;
        }

        // submitToActChemicalDB creates or merges as necessary.
        Long id = db.getNextAvailableChemicalDBid();
        db.submitToActChemicalDB(chem, id);
        LOGGER.debug("Submitted chemical %d to the DB", id);
    }
    LOGGER.info("Loaded %d HMDB chemicals into DB", files.size());
}

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

/**
 * Initializes Terraform so it can execute the given commands.
 * Here is the order of operations://w ww .j  a v  a  2 s.c  o 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.gargoylesoftware.htmlunit.xml.XmlPage.java

/**
 * Creates an instance.//  w  ww.j a v  a  2 s . c o  m
 * A warning is logged if an exception is thrown while parsing the XML content
 * (for instance when the content is not a valid XML and can't be parsed).
 *
 * @param webResponse the response from the server
 * @param enclosingWindow the window that holds the page
 * @param ignoreSAXException Whether to ignore {@link SAXException} or throw it as {@link IOException}
 * @param handleXHTMLAsHTML if true elements from the XHTML namespace are handled as HTML elements instead of
 *     DOM elements
 * @throws IOException if the page could not be created
 */
public XmlPage(final WebResponse webResponse, final WebWindow enclosingWindow, final boolean ignoreSAXException,
        final boolean handleXHTMLAsHTML) throws IOException {
    super(webResponse, enclosingWindow);

    try {
        try {
            final Document document = XmlUtil.buildDocument(webResponse);
            node_ = document.getFirstChild();
        } catch (final SAXException e) {
            LOG.warn("Failed parsing XML document " + webResponse.getWebRequest().getUrl() + ": "
                    + e.getMessage());
            if (!ignoreSAXException) {
                throw new IOException(e.getMessage());
            }
        }
    } catch (final ParserConfigurationException e) {
        if (null == webResponse) {
            LOG.warn("Failed parsing XML empty document: " + e.getMessage());
        } else {
            LOG.warn("Failed parsing XML empty document " + webResponse.getWebRequest().getUrl() + ": "
                    + e.getMessage());
        }
    }

    Node node = node_;
    while (node != null) {
        XmlUtil.appendChild(this, this, node, handleXHTMLAsHTML);
        node = node.getNextSibling();
    }
}

From source file:com.fujitsu.dc.test.jersey.cell.auth.ImplicitFlowTest.java

static void checkHtmlBody(DcResponse res, String messageId, String dataCellName, String dcOwner) {
        DOMParser parser = new DOMParser();
        InputSource body = null;//from w  w w .  j ava 2  s .com
        body = new InputSource(res.bodyAsStream());
        try {
            parser.parse(body);
        } catch (SAXException e) {
            fail(e.getMessage());
        } catch (IOException e) {
            fail(e.getMessage());
        }
        Document document = parser.getDocument();
        NodeList nodeList = document.getElementsByTagName("script");
        assertEquals(AuthResourceUtils.getJavascript("ajax.js"), ((Element) nodeList.item(0)).getTextContent());

        nodeList = document.getElementsByTagName("title");
        assertEquals(DcCoreMessageUtils.getMessage("PS-AU-0001"), ((Element) nodeList.item(0)).getTextContent());

        nodeList = document.getElementsByTagName("body");
        String expectedAppUrl = UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA1) + "__/profile.json";
        String expectedDataUrl = UrlUtils.cellRoot(dataCellName) + "__/profile.json";
        assertEquals("requestFile('GET', '" + expectedAppUrl + "' , '" + expectedDataUrl + "' ,true )",
                ((Element) nodeList.item(0)).getAttribute("onload"));

        nodeList = document.getElementsByTagName("h1");
        assertEquals(DcCoreMessageUtils.getMessage("PS-AU-0001"), ((Element) nodeList.item(0)).getTextContent());

        nodeList = document.getElementsByTagName("form");
        String expectedFormUrl = UrlUtils.cellRoot(dataCellName) + "__authz";
        assertEquals(expectedFormUrl, ((Element) nodeList.item(0)).getAttribute("action"));

        nodeList = document.getElementsByTagName("div");
        for (int i = 0; i < nodeList.getLength(); i++) {
            Element element = (Element) nodeList.item(i);
            String id = element.getAttribute("id");
            if ("message".equals(id)) {
                assertEquals(DcCoreMessageUtils.getMessage(messageId).replaceAll("<br />", ""),
                        element.getTextContent());
            }
        }

        nodeList = document.getElementsByTagName("input");
        for (int i = 0; i < nodeList.getLength(); i++) {
            Element element = (Element) nodeList.item(i);
            String id = element.getAttribute("id");
            if ("state".equals(id)) {
                assertEquals(DEFAULT_STATE, element.getAttribute("value"));
            } else if ("dc_target".equals(id)) {
                assertEquals("", element.getAttribute("value"));

            } else if ("dc_owner".equals(id)) {
                assertEquals(dcOwner, element.getAttribute("value"));
            } else if ("client_id".equals(id)) {
                assertEquals(UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA1), element.getAttribute("value"));
            } else if ("redirect_uri".equals(id)) {
                assertEquals(UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA1) + REDIRECT_HTML,
                        element.getAttribute("value"));
            }
        }
    }

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

static synchronized public Document parse(String fileName) throws IOException {
    try {/*from  w ww .ja v  a  2s.co  m*/
        return ensureDocumentBuilder().parse(fileName);
    } catch (SAXException e) {
        log.error("Error parsing fileName [" + fileName + "]; " + e.getMessage(), e);
    }

    return null;
}

From source file:com.keithhutton.ws.proxy.ProxyServlet.java

private XmlRpcRequest getMethodAndParamsFromRequest(ServletRequest req) throws XmlRpcException {
    final XmlRpcStreamRequestConfig pConfig = getConfig((HttpServletRequest) req);
    final XmlRpcRequestParser parser = new XmlRpcRequestParser(pConfig, getTypeFactory());
    final XMLReader xr = SAXParsers.newXMLReader();
    xr.setContentHandler(parser);//  w  w w .  jav a2  s.  co m
    try {
        xr.parse(new InputSource(req.getInputStream()));
    } catch (SAXException e) {
        Exception ex = e.getException();
        if (ex != null && ex instanceof XmlRpcException) {
            throw (XmlRpcException) ex;
        }
        throw new XmlRpcException("Failed to parse XML-RPC request: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new XmlRpcException("Failed to read XML-RPC request: " + e.getMessage(), e);
    }
    final List params = parser.getParams();
    final int paramCount = params == null ? 0 : params.size();
    XmlRpcRequest xmlRpcRequest = new XmlRpcRequest() {
        public XmlRpcRequestConfig getConfig() {
            return pConfig;
        }

        public String getMethodName() {
            return parser.getMethodName();
        }

        public int getParameterCount() {
            return params == null ? 0 : params.size();
        }

        public Object getParameter(int pIndex) {
            return paramCount > 0 ? params.get(pIndex) : null;
        }
    };
    this.log.info("xmlRpcRequest method = " + xmlRpcRequest.getMethodName());
    this.log.info("xmlRpcRequest pcount = " + xmlRpcRequest.getParameterCount());
    this.log.info("xmlRpcRequest param1 = " + xmlRpcRequest.getParameter(0));
    return xmlRpcRequest;

}

From source file:net.sf.joost.trax.TemplatesImpl.java

/**
 * Configures the <code>Templates</code> - initializing by parsing the
 * stylesheet./*from  w  w  w  . j a  va 2 s. c  o m*/
 * @param reader The <code>XMLReader</code> for parsing the stylesheet
 * @param isource The <code>InputSource</code> of the stylesheet
 * @throws TransformerConfigurationException When an error occurs while
 *  initializing the <code>Templates</code>.
 */
private void init(XMLReader reader, InputSource isource) throws TransformerConfigurationException {

    if (DEBUG)
        log.debug("init with InputSource " + isource.getSystemId());
    try {
        /**
         * Register ErrorListener from
         * {@link TransformerFactoryImpl#getErrorListener()}
         * if available.
         */
        // check if transformerfactory is in debug mode
        boolean debugmode = ((Boolean) this.factory.getAttribute(DEBUG_FEATURE)).booleanValue();

        ParseContext pContext = new ParseContext();
        pContext.allowExternalFunctions = factory.allowExternalFunctions;
        pContext.setErrorListener(factory.getErrorListener());
        pContext.uriResolver = factory.getURIResolver();
        if (debugmode) {
            if (DEBUG)
                log.info("init transformer in debug mode");
            pContext.parserListener = factory.getParserListenerMgr();
            processor = new DebugProcessor(reader, isource, pContext, factory.getMessageEmitter());
        } else {
            processor = new Processor(reader, isource, pContext);
        }
        processor.setTransformerHandlerResolver(factory.thResolver);
        processor.setOutputURIResolver(factory.outputUriResolver);
    } catch (java.io.IOException iE) {
        if (DEBUG)
            log.debug(iE);
        throw new TransformerConfigurationException(iE.getMessage(), iE);
    } catch (org.xml.sax.SAXException sE) {
        Exception emb = sE.getException();
        if (emb instanceof TransformerConfigurationException)
            throw (TransformerConfigurationException) emb;
        if (DEBUG)
            log.debug(sE);
        throw new TransformerConfigurationException(sE.getMessage(), sE);
    } catch (java.lang.NullPointerException nE) {
        if (DEBUG)
            log.debug(nE);
        nE.printStackTrace(System.err);
        throw new TransformerConfigurationException(
                "could not found value for property javax.xml.parsers.SAXParser ", nE);
    }
}

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

private void processFile(File file) {

    try {//from  ww  w. jav  a2  s. co 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:XMLProperties.java

/**
 * Reads a property list from an input stream. This method try to load
 * properties with super.load() if the XMLParser failed. Use this method to
 * translate an Property set to an XML Property set.
 * //w  w  w  .  j  av  a2s.c om
 * @param file
 *          the properties file.
 * @exception IOException
 *              if an error occurred when reading from the input stream.
 * @since JDK1.0
 */
public synchronized void load(File file) throws IOException {
    InputStream in = new BufferedInputStream(new FileInputStream(file));
    XMLParser p = null;
    try {
        p = new XMLParser(in);
    } catch (SAXException e) {
        try {
            in = new BufferedInputStream(new FileInputStream(file));
            super.load(in);
            in.close();
        } catch (IOException ex) {
            throw new IOException(e.getMessage());
        }
    }
}