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:com.wwpass.connection.WWPassConnection.java

private static InputStream getReplyData(final InputStream rawXMLInput)
        throws IOException, WWPassProtocolException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document dom;/*from   ww w. j  a va 2 s . c  o m*/
    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:io.personium.test.jersey.cell.auth.ImplicitFlowTest.java

static void checkHtmlBody(PersoniumResponse res, String messageId, String dataCellName, String dcOwner) {
        DOMParser parser = new DOMParser();
        InputSource body = null;//from  w w w. j  av  a 2 s.c o  m
        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(PersoniumCoreMessageUtils.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(PersoniumCoreMessageUtils.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(PersoniumCoreMessageUtils.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 ("p_target".equals(id)) {
                assertEquals("", element.getAttribute("value"));

            } else if ("p_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.github.tomakehurst.wiremock.matching.ValuePattern.java

private boolean isXPathMatch(String value) {
    try {//from   w  ww  . j  av  a  2  s . c o m
        Document inDocument = XMLUnit.buildControlDocument(value);
        XpathEngine simpleXpathEngine = XMLUnit.newXpathEngine();
        if (xpathNamespaces != null) {
            NamespaceContext namespaceContext = new SimpleNamespaceContext(xpathNamespaces);
            simpleXpathEngine.setNamespaceContext(namespaceContext);
        }
        NodeList nodeList = simpleXpathEngine.getMatchingNodes(matchesXPath, inDocument);
        return nodeList.getLength() > 0;
    } catch (SAXException e) {
        notifier().info(String.format("Warning: failed to parse the XML document. Reason: %s\nXML: %s",
                e.getMessage(), value));
        return false;
    } catch (IOException e) {
        notifier().info(e.getMessage());
        return false;
    } catch (XpathException e) {
        notifier().info("Warning: failed to evaluate the XPath expression " + matchesXPath);
        return false;
    }
}

From source file:com.evolveum.midpoint.common.validator.Validator.java

public Node validateSchema(Element objectDoc, OperationResult objectResult) {
    OperationResult result = objectResult.createSubresult(Validator.class.getName() + ".validateSchema");
    DOMResult validationResult = new DOMResult();
    try {/*from  w w  w  .j a va  2s.  c  o  m*/
        xsdValidator.validate(new DOMSource(objectDoc), validationResult);
    } catch (SAXException e) {
        result.recordFatalError("Validation error: " + e.getMessage(), e);
        objectResult.computeStatus("Validation error: " + e.getMessage());
        return null;
    } catch (IOException e) {
        result.recordFatalError("IO error during validation: " + e.getMessage(), e);
        objectResult.computeStatus("IO error during validation: " + e.getMessage());
        return null;
    }
    result.recordSuccess();
    return validationResult.getNode();
}

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

/**
 * Creates a new AbstractHostKeyVerification object.
 *
 * @param hostFileName//ww  w .j  a  v  a2  s . co 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) {
            }
        }
    }
}

From source file:de.uzk.hki.da.cb.CreatePremisAction.java

/**
 * @throws FileNotFoundException if one or more of the jhove output files are not present.
 *///from w  w w  .  j  a  va  2s .  c om
@Override
public boolean implementation() throws IOException {
    logger.debug("Listing all files attached to all packages of the object:");
    for (Package pkg : o.getPackages())
        for (DAFile fi : pkg.getFiles())
            logger.debug(fi.toString());

    determineSizeForAllFiles();

    Object newPREMISObject = new Object();
    newPREMISObject.setOrig_name(o.getOrig_name());
    newPREMISObject.setIdentifier(o.getIdentifier());
    newPREMISObject.setUrn(o.getUrn());
    newPREMISObject.setContractor(o.getContractor());
    newPREMISObject.setDdbExclusion(o.ddbExcluded());
    newPREMISObject.setLicense_flag(o.getLicense_flag());

    Object sipPREMISObject = parsePremisFile(
            new File(Path.make(wa.dataPath(), o.getNameOfLatestBRep(), PREMIS).toString().replace("+b", "+a")));

    if (sipPREMISObject.getPackages().size() > 0) {
        o.getLatestPackage().getEvents().addAll(sipPREMISObject.getPackages().get(0).getEvents());
        addedEvents.addAll(sipPREMISObject.getPackages().get(0).getEvents());
    }

    newPREMISObject.setRights(sipPREMISObject.getRights());
    newPREMISObject.getRights().setId(o.getIdentifier() + "#rights");
    newPREMISObject.getAgents().addAll(sipPREMISObject.getAgents());

    Event ingestEventElement = generateIngestEventElement();
    o.getLatestPackage().getEvents().add(ingestEventElement);
    addedEvents.add(ingestEventElement);

    newPREMISObject.getPackages().add(o.getLatestPackage());

    if (o.isDelta()) {
        deserializeOldPremisFile(newPREMISObject);
    }

    checkConvertEvents(newPREMISObject);

    File newPREMISXml = Path.make(wa.dataPath(), o.getNameOfLatestBRep(), PREMIS).toFile();
    logger.trace("trying to write new Premis file at " + newPREMISXml.getAbsolutePath());
    new ObjectPremisXmlWriter().serialize(newPREMISObject, newPREMISXml,
            Path.make(wa.dataPath(), "jhove_temp"));

    try {
        if (!PremisXmlValidator.validatePremisFile(newPREMISXml))
            throw new RuntimeException("PREMIS that has recently been created is not valid");
    } catch (SAXException e) {
        logger.error(e.getMessage());
        throw new RuntimeException("PREMIS that has recently been created is not valid: " + e.getMessage());
    }
    logger.trace("Successfully created premis file");
    o.getLatestPackage().getFiles().add(new DAFile(j.getRep_name() + "b", PREMIS));

    for (Package p : newPREMISObject.getPackages()) {
        logger.debug("pname:" + p.getName());
    }

    determineDisclosureLimits(newPREMISObject);
    deleteJhoveTempFiles();

    return true;
}

From source file:org.energyos.espi.common.service.impl.ImportServiceImpl.java

@Override
public void importData(InputStream stream, Long retailCustomerId)
        throws IOException, SAXException, ParserConfigurationException {

    // setup the parser
    JAXBContext context = marshaller.getJaxbContext();

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);/*from  w w  w .  ja v a 2s.c  om*/
    XMLReader reader = factory.newSAXParser().getXMLReader();

    // EntryProcessor processor = new EntryProcessor(resourceLinker, new
    // ResourceConverter(), resourceService);
    ATOMContentHandler atomContentHandler = new ATOMContentHandler(context, entryProcessorService);
    reader.setContentHandler(atomContentHandler);

    // do the parse/import

    try {
        reader.parse(new InputSource(stream));

    } catch (SAXException e) {
        System.out.printf(
                "\nImportServiceImpl -- importData: SAXException\n     Cause = %s\n     Description = %s\n\n",
                e.getClass(), e.getMessage());
        throw new SAXException(e.getMessage(), e);

    } catch (Exception e) {
        System.out.printf("\nImportServiceImpl -- importData:\n     Cause = %s\n     Description = %s\n\n",
                e.getClass(), e.getMessage());
        e.printStackTrace();

    }
    // context of the import used for linking things up
    // and establishing notifications
    //

    entries = atomContentHandler.getEntries();
    minUpdated = atomContentHandler.getMinUpdated();
    maxUpdated = atomContentHandler.getMaxUpdated();

    // cleanup/end processing
    // 1 - associate to usage points to the right retail customer
    // 2 - make sure authorization/subscriptions have the right URIs
    // 3 - place the imported usagePoints in to the subscriptions
    //
    List<UsagePoint> usagePointList = new ArrayList<UsagePoint>();

    // now perform any associations (to RetailCustomer) and stage the
    // Notifications (if any)

    RetailCustomer retailCustomer = null;

    if (retailCustomerId != null) {
        retailCustomer = retailCustomerService.findById(retailCustomerId);
    }

    Iterator<EntryType> its = entries.iterator();

    while (its.hasNext()) {
        EntryType entry = its.next();
        UsagePoint usagePoint = entry.getContent().getUsagePoint();
        if (usagePoint != null) {

            // see if we already have a retail customer association

            RetailCustomer tempRc = usagePoint.getRetailCustomer();
            if (tempRc != null) {
                // hook it to the retailCustomer
                if (!(tempRc.equals(retailCustomer))) {
                    // we have a conflict in association meaning to Retail
                    // Customers
                    // TODO: resolve how to handle the conflict mentioned
                    // above.
                    // TODO: Only works for a single customer and not
                    // multiple customers
                    retailCustomer = tempRc;
                }
            } else {
                // associate the usagePoint with the Retail Customer
                if (retailCustomer != null) {
                    usagePointService.associateByUUID(retailCustomer, usagePoint.getUUID());
                }
            }
            usagePointList.add(usagePoint);
        }
    }

    // now if we have a retail customer, check for any subscriptions that
    // need associated
    if (retailCustomer != null) {

        Subscription subscription = null;

        // find and iterate across all relevant authorizations
        //
        List<Authorization> authorizationList = authorizationService
                .findAllByRetailCustomerId(retailCustomer.getId());
        for (Authorization authorization : authorizationList) {

            try {
                subscription = subscriptionService.findByAuthorizationId(authorization.getId());
            } catch (Exception e) {
                // an Authorization w/o an associated subscription breaks
                // the propagation chain
                System.out.printf("**** End of Notification Propagation Chain\n");
            }
            if (subscription != null) {
                String resourceUri = authorization.getResourceURI();
                // this is the first time this authorization has been in
                // effect. We must set up the appropriate resource links
                if (resourceUri == null) {
                    ApplicationInformation applicationInformation = authorization.getApplicationInformation();
                    resourceUri = applicationInformation.getDataCustodianResourceEndpoint();
                    resourceUri = resourceUri + "/Batch/Subscription/" + subscription.getId();
                    authorization.setResourceURI(resourceUri);

                    resourceService.merge(authorization);
                }

                // make sure the UsagePoint(s) we just imported are linked
                // up
                // with
                // the Subscription

                for (UsagePoint usagePoint : usagePointList) {
                    boolean addNew = false;
                    for (UsagePoint up : subscription.getUsagePoints()) {
                        if (up.equals(usagePoint))
                            addNew = true;
                    }

                    if (addNew)
                        subscriptionService.addUsagePoint(subscription, usagePoint);

                }
            }
        }
    }
}

From source file:com.vmware.photon.controller.model.adapters.vsphere.ovf.OvfRetriever.java

private StoringInputStream toStream(URI ovfUri) throws IOException {
    SAXParser saxParser = newSaxParser();
    DefaultHandler handler = new DefaultHandler();

    InputStream is;//from w ww .j a v a2 s. co  m
    HttpResponse response = null;
    HttpGet request = null;

    if (ovfUri.getScheme().equals("file")) {
        is = new FileInputStream(new File(ovfUri));
    } else {
        request = new HttpGet(ovfUri);
        response = this.client.execute(request);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new IOException(
                    "Ovf descriptor not found at " + ovfUri + ". Error code " + response.getStatusLine());
        }

        is = response.getEntity().getContent();
    }

    StoringInputStream storingInputStream = new StoringInputStream(is);

    try {
        saxParser.parse(storingInputStream, handler);
        if (response != null) {
            EntityUtils.consumeQuietly(response.getEntity());
        }
    } catch (SAXException e) {
        // not a valid ovf - abort
        if (request != null) {
            request.abort();
        }
        EntityUtils.consumeQuietly(response.getEntity());

        throw new IOException("Ovf not a valid xml: " + e.getMessage(), e);
    } finally {
        //close stream, could be file
        IOUtils.closeQuietly(is);
    }

    return storingInputStream;
}

From source file:eu.esdihumboldt.hale.io.appschema.writer.AppSchemaFileWriterTest.java

private boolean isMappingValid(File mappingFile) throws IOException {
    URL mappingSchema = getClass().getResource(MAPPING_SCHEMA);
    Source xmlFile = new StreamSource(mappingFile);
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    javax.xml.validation.Schema schema = null;
    try {/*from  ww w  .  j  av  a2s  . com*/
        schema = schemaFactory.newSchema(mappingSchema);
    } catch (SAXException e) {
        fail("Exception parsing mapping schema: " + e.getMessage());
    }

    @SuppressWarnings("null")
    Validator validator = schema.newValidator();
    try {
        validator.validate(xmlFile);
        return true;
    } catch (SAXException e) {
        log.error("Mapping file validation failed", e);
        return false;
    }
}

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

/**
 * Creates an <code>XMLFilter</code> that uses the given <code>Source</code>
 * as the transformation instructions./* w  w w  .  j a v  a 2 s  .  c o m*/
 * Implementation of the {@link SAXTransformerFactory}
 * @param src - The Source of the transformation instructions.
 * @return An {@link XMLFilter} object, or <code>null</code> if this feature is not
 *  supported.
 * @throws TransformerConfigurationException
 */
public XMLFilter newXMLFilter(Source src) throws TransformerConfigurationException {

    if (DEBUG)
        if (log.isDebugEnabled())
            log.debug("getting SAXTransformerFactory.FEATURE_XMLFILTER " + "from Source " + src.getSystemId());
    XMLFilter xFilter = null;
    try {
        Templates templates = newTemplates(src);
        //get a XMLReader
        XMLReader parser = Processor.createXMLReader();
        xFilter = newXMLFilter(templates);
        xFilter.setParent(parser);
        return xFilter;
    } catch (SAXException ex) {
        TransformerConfigurationException tE = new TransformerConfigurationException(ex.getMessage(), ex);
        defaultErrorListener.fatalError(tE);
        return null;
    }
}