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.roda.core.common.validation.ValidationUtils.java

/**
 * Validates preservation medatada (e.g. against its schema, but other
 * strategies may be used)// w  w w.j  av  a2  s. c o m
 * 
 * @param failIfNoSchema
 * 
 * @param descriptiveMetadataId
 * 
 * @param failIfNoSchema
 * @throws ValidationException
 */
public static ValidationReport validatePreservationBinary(Binary binary, boolean failIfNoSchema) {
    ValidationReport report = new ValidationReport();
    InputStream inputStream = null;
    try {
        Optional<Schema> xmlSchema = RodaCoreFactory.getRodaSchema("premis-v2-0", null);
        if (xmlSchema.isPresent()) {
            inputStream = binary.getContent().createInputStream();
            Source xmlFile = new StreamSource(inputStream);
            Validator validator = xmlSchema.get().newValidator();
            RodaErrorHandler errorHandler = new RodaErrorHandler();
            validator.setErrorHandler(errorHandler);
            try {
                validator.validate(xmlFile);
                report.setValid(errorHandler.getErrors().isEmpty());
                for (SAXParseException saxParseException : errorHandler.getErrors()) {
                    report.addIssue(convertSAXParseException(saxParseException));
                }
            } catch (SAXException e) {
                LOGGER.error("Error validating preservation binary " + binary.getStoragePath(), e);
                report.setValid(false);
                for (SAXParseException saxParseException : errorHandler.getErrors()) {
                    report.addIssue(convertSAXParseException(saxParseException));
                }
            }
        } else if (failIfNoSchema) {
            report.setValid(false);
            report.setMessage("No schema to validate PREMIS");
        }

    } catch (IOException e) {
        report.setValid(false);
        report.setMessage(e.getMessage());
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
    return report;

}

From source file:org.roda.wui.api.controllers.BrowserHelper.java

public static DescriptiveMetadataEditBundle retrieveDescriptiveMetadataEditBundle(User user, IndexedAIP aip,
        IndexedRepresentation representation, String descriptiveMetadataId, String type, String version,
        final Locale locale)
        throws GenericException, RequestNotValidException, NotFoundException, AuthorizationDeniedException {
    DescriptiveMetadataEditBundle ret;//from w w w . j av  a 2s  .  co  m
    InputStream inputStream = null;
    try {
        String representationId = representation != null ? representation.getId() : null;
        Binary binary = RodaCoreFactory.getModelService().retrieveDescriptiveMetadataBinary(aip.getId(),
                representationId, descriptiveMetadataId);
        inputStream = binary.getContent().createInputStream();
        String xml = IOUtils.toString(inputStream, "UTF-8");

        // Get the supported metadata type with the same type and version
        // We need this to try to get get the values for the form
        SupportedMetadataTypeBundle metadataTypeBundle = null;
        List<SupportedMetadataTypeBundle> supportedMetadataTypeBundles = BrowserHelper
                .retrieveSupportedMetadata(user, aip, representation, locale);
        for (SupportedMetadataTypeBundle typeBundle : supportedMetadataTypeBundles) {
            if (typeBundle.getType() != null && typeBundle.getType().equalsIgnoreCase(type)) {
                if (typeBundle.getVersion() != null && typeBundle.getVersion().equalsIgnoreCase(version)) {
                    metadataTypeBundle = typeBundle;
                    break;
                }
            }
        }

        boolean similar = false;
        // Get the values using XPath
        Set<MetadataValue> values = null;
        String template = null;

        if (metadataTypeBundle != null) {
            values = metadataTypeBundle.getValues();
            template = metadataTypeBundle.getTemplate();
            if (values != null) {
                for (MetadataValue mv : values) {
                    // clear the auto-generated values
                    // mv.set("value", null);
                    String xpathRaw = mv.get("xpath");
                    if (xpathRaw != null && xpathRaw.length() > 0) {
                        String[] xpaths = xpathRaw.split("##%##");
                        String value;
                        List<String> allValues = new ArrayList<>();
                        for (String xpath : xpaths) {
                            allValues.addAll(ServerTools.applyXpath(xml, xpath));
                        }
                        // if any of the values is different, concatenate all values in a
                        // string, otherwise return the value
                        boolean allEqual = allValues.stream()
                                .allMatch(s -> s.trim().equals(allValues.get(0).trim()));
                        if (allEqual && !allValues.isEmpty()) {
                            value = allValues.get(0);
                        } else {
                            value = String.join(" / ", allValues);
                        }
                        mv.set("value", value.trim());
                    }
                }

                // Identity check. Test if the original XML is equal to the result of
                // applying the extracted values to the template
                metadataTypeBundle.setValues(values);
                String templateWithValues = retrieveDescriptiveMetadataPreview(metadataTypeBundle);
                try {
                    XMLUnit.setIgnoreComments(true);
                    XMLUnit.setIgnoreWhitespace(true);
                    XMLUnit.setIgnoreAttributeOrder(true);
                    XMLUnit.setCompareUnmatched(false);

                    Diff xmlDiff = new Diff(xml, templateWithValues);
                    xmlDiff.overrideDifferenceListener(new XMLSimilarityIgnoreElements("schemaLocation"));
                    similar = xmlDiff.identical() || xmlDiff.similar();
                } catch (SAXException e) {
                    LOGGER.warn("Could not check if template can loose info", e);
                }
            }
        }

        ret = new DescriptiveMetadataEditBundle(descriptiveMetadataId, type, version, xml, template, values,
                similar);
    } catch (IOException e) {
        throw new GenericException("Error getting descriptive metadata edit bundle: " + e.getMessage());
    } finally {
        IOUtils.closeQuietly(inputStream);
    }

    return ret;
}

From source file:org.sakaibrary.osid.repository.xserver.AssetIterator.java

/**
 * This method parses the xml StringBuilder and creates Assets, Records
 * and Parts in the Repository with the given repositoryId.
 *
 * @param xml input xml in "sakaibrary" format
 * @param log the log being used by the Repository
 * @param repositoryId the Id of the Repository in which to create Assets,
 * Records and Parts.//  w  ww  .j av  a  2 s  .c  o  m
 *
 * @throws org.osid.repository.RepositoryException
 */
private void createAssets(java.io.ByteArrayInputStream xml, org.osid.shared.Id repositoryId)
        throws org.osid.repository.RepositoryException {
    this.repositoryId = repositoryId;
    recordStructureId = RecordStructure.getInstance().getId();
    textBuffer = new StringBuilder();

    // use a SAX parser
    javax.xml.parsers.SAXParserFactory factory;
    javax.xml.parsers.SAXParser saxParser;

    // set up the parser
    factory = javax.xml.parsers.SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);

    // start parsing
    try {
        saxParser = factory.newSAXParser();
        saxParser.parse(xml, this);
        xml.close();
    } catch (SAXParseException spe) {
        // Use the contained exception, if any
        Exception x = spe;

        if (spe.getException() != null) {
            x = spe.getException();
        }

        // Error generated by the parser
        LOG.warn("createAssets() parsing exception: " + spe.getMessage() + " - xml line " + spe.getLineNumber()
                + ", uri " + spe.getSystemId(), x);
    } catch (SAXException sxe) {
        // Error generated by this application
        // (or a parser-initialization error)
        Exception x = sxe;

        if (sxe.getException() != null) {
            x = sxe.getException();
        }

        LOG.warn("createAssets() SAX exception: " + sxe.getMessage(), x);
    } catch (ParserConfigurationException pce) {
        // Parser with specified options can't be built
        LOG.warn("createAssets() SAX parser cannot be built with " + "specified options");
    } catch (IOException ioe) {
        // I/O error
        LOG.warn("createAssets() IO exception", ioe);
    }
}

From source file:org.sakaibrary.xserver.XMLCleanup.java

public ByteArrayOutputStream cleanup(InputStream xml) throws XServerException {
    inputXml = xml;//from  w  ww  . ja  v  a 2s.c  o m

    // Use the default (non-validating) parser
    SAXParserFactory factory = SAXParserFactory.newInstance();

    try {
        // Parse the input
        SAXParser saxParser = factory.newSAXParser();
        saxParser.parse(inputXml, this);

        // close the stream
        inputXml.close();
    } catch (SAXParseException spe) {
        // Use the contained exception, if any
        Exception x = spe;

        if (spe.getException() != null) {
            x = spe.getException();
        }

        // Error generated by the parser
        LOG.warn("XMLCleanup.cleanup() parsing exception: " + spe.getMessage() + " - xml line "
                + spe.getLineNumber() + ", uri " + spe.getSystemId(), x);
    } catch (SAXException sxe) {
        // Error generated by this application
        // (or a parser-initialization error)
        Exception x = sxe;

        if (sxe.getException() != null) {
            x = sxe.getException();
        }

        LOG.warn("XMLCleanup.cleanup() SAX exception: " + sxe.getMessage(), x);
    } catch (ParserConfigurationException pce) {
        // Parser with specified options can't be built
        LOG.warn("XMLCleanup.cleanup() SAX parser cannot be built with " + "specified options");
    } catch (IOException ioe) {
        // I/O error
        LOG.warn("XMLCleanup.cleanup() IO exception", ioe);
    } catch (Throwable t) {
        LOG.warn("XMLCleanup.cleanup() exception", t);
    }

    if (error) {
        throw new XServerException(error_code, error_text);
    }

    return bytes;
}

From source file:org.sakaibrary.xserver.XMLTransform.java

public ByteArrayOutputStream transform() {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    try {//from w ww .  ja  v a  2s .  c om
        InputStream stylesheet = this.getClass().getResourceAsStream(xslFileName);

        DocumentBuilder builder = factory.newDocumentBuilder();
        document = builder.parse(new ByteArrayInputStream(xml.toByteArray()));

        // Use a Transformer for output
        TransformerFactory tFactory = TransformerFactory.newInstance();
        StreamSource stylesource = new StreamSource(stylesheet);
        Transformer transformer = tFactory.newTransformer(stylesource);

        transformedXml = new ByteArrayOutputStream();
        StreamResult result = new StreamResult(transformedXml);

        DOMSource source = new DOMSource(document);

        transformer.transform(source, result);
    } catch (TransformerConfigurationException tce) {
        // Error generated by the parser
        LOG.warn("XMLTransform.transform() - TransformerFactory error: " + tce.getMessage());
    } catch (TransformerException te) {
        // Error generated by the parser
        LOG.warn("XMLTransform.transform() - Transformation error: " + te.getMessage());
    } catch (SAXException sxe) {
        // Error generated by this application
        // (or a parser-initialization error)
        Exception x = sxe;

        if (sxe.getException() != null) {
            x = sxe.getException();
        }

        LOG.warn("XMLTransform.transform() SAX exception: " + sxe.getMessage(), x);
    } catch (ParserConfigurationException pce) {
        // Parser with specified options can't be built
        LOG.warn("XMLTransform.transform() SAX parser cannot be built with " + "specified options");
    } catch (IOException ioe) {
        // I/O error
        LOG.warn("XMLCleanup.cleanup() IO exception", ioe);
    }

    return transformedXml;
}

From source file:org.sakaibrary.xserver.XServer.java

/**
 * Creates a new XServer object ready to communicate with the
 * MetaLib X-server.  Reads searchProperties, sets up SAX Parser, and
 * sets up session management for this object.
 *///from   w  w w.j ava  2  s . co  m
public XServer(String guid) throws XServerException {
    this.guid = guid;

    // setup the SAX parser
    SAXParserFactory factory;
    factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    try {
        saxParser = factory.newSAXParser();
    } catch (SAXException sxe) {
        // Error generated by this application
        // (or a parser-initialization error)
        Exception x = sxe;

        if (sxe.getException() != null) {
            x = sxe.getException();
        }

        LOG.warn("XServer() SAX exception in trying to get a new SAXParser " + "from SAXParserFactory: "
                + sxe.getMessage(), x);
        throw new RuntimeException("XServer() SAX exception: " + sxe.getMessage(), x);
    } catch (ParserConfigurationException pce) {
        // Parser with specified options can't be built
        LOG.warn("XServer() SAX parser cannot be built with specified options");
        throw new RuntimeException(
                "XServer() SAX parser cannot be built with " + "specified options: " + pce.getMessage(), pce);
    }

    // load session state
    msm = MetasearchSessionManager.getInstance();
    MetasearchSession metasearchSession = msm.getMetasearchSession(guid);

    if (metasearchSession == null) {
        // bad state management
        throw new RuntimeException("XServer() - cache MetasearchSession is " + "NULL :: guid is " + guid);
    }

    // get X-Server base URL
    xserverBaseUrl = metasearchSession.getBaseUrl();

    if (!metasearchSession.isLoggedIn()) {
        // need to login
        username = metasearchSession.getUsername();
        password = metasearchSession.getPassword();

        if (!loginURL(username, password)) {
            // authorization failed
            throw new XServerException("XServer.loginURL()", "authorization failed.");
        }

        // login success
        metasearchSession.setLoggedIn(true);
        metasearchSession.setSessionId(sessionId);
    }

    // get search properties
    org.osid.shared.Properties searchProperties = metasearchSession.getSearchProperties();

    try {
        searchSourceIds = (ArrayList) searchProperties.getProperty("searchSourceIds"); // empty TODO
        sortBy = (String) searchProperties.getProperty("sortBy");
        pageSize = (Integer) searchProperties.getProperty("pageSize");
        startRecord = (Integer) searchProperties.getProperty("startRecord");
    } catch (org.osid.shared.SharedException se) {
        LOG.warn("XServer() failed to get search properties - will assign " + "defaults", se);
    }

    // assign defaults if necessary
    // TODO assign the updated values to the session... searchProperties is read-only, need to add additional fields to MetasearchSession.
    if (sortBy == null) {
        sortBy = "rank";
    }

    if (pageSize == null) {
        pageSize = new Integer(10);
    }

    if (startRecord == null) {
        startRecord = new Integer(1);
    }

    // check args
    if (startRecord.intValue() <= 0) {
        LOG.warn("XServer() - startRecord must be set to 1 or higher.");
        startRecord = null;
        startRecord = new Integer(1);
    }

    // add/update this MetasearchSession in the cache
    msm.putMetasearchSession(guid, metasearchSession);
}

From source file:org.sakaibrary.xserver.XServer.java

/**
 * Logs a user into the X-server using URL Syntax for communications.
 * Uses the login X-service./*  ww  w.  j  a  va 2s .  c om*/
 *
 * @param username String representing user username
 * @param password String representing user password
 *
 * @return boolean true if authorization succeeds, false otherwise.
 *
 * @throws XServerException if login fails due to X-server error
 */
private boolean loginURL(String username, String password) throws XServerException {
    // build URL query string
    StringBuilder query = new StringBuilder(xserverBaseUrl);
    query.append("?op=login_request&user_name=" + username + "&user_password=" + password);

    // connect to URL and get response
    java.io.ByteArrayOutputStream xml = doURLConnection(query.toString());

    if (printXML) {
        // print xml
        LOG.debug(xml.toString());
    }

    // run SAX Parser
    try {
        saxParseXML(new java.io.ByteArrayInputStream(xml.toByteArray()));
    } catch (SAXException sxe) {
        // Error generated by this application
        // (or a parser-initialization error)
        Exception x = sxe;

        if (sxe.getException() != null) {
            x = sxe.getException();
        }

        LOG.warn("loginURL() SAX exception: " + sxe.getMessage(), x);
    } catch (IOException ioe) {
        // I/O error
        LOG.warn("loginURL() IO exception", ioe);
    }

    // return whether or not the login was successful
    return (loginSuccessful());
}

From source file:org.sakaibrary.xserver.XServer.java

/**
 * Finds records within the given sources using the given find command
 * query.  Uses the find X-service./*from  ww  w.ja  va 2  s.com*/
 *
 * @param findCommand String representing find_request_command.  See
 *   <a href="http://searchtools.lib.umich.edu/X/?op=explain&func=find">
 *   find</a> explanation from MetaLib X-Server to see how
 *   find_request_command should be built.
 *
 * @param waitFlag String representing the wait_flag.  A "Y" indicates
 *   the X-server will not produce a response until the find command has
 *   completed.  Full information about the group and each search set will
 *   be returned.
 *   <br></br>
 *   A "N" indicates the X-server will immediately respond with the group
 *   number while the find continues to run in the background.  The user
 *   can then use the findGroupInfo method to poll for results.
 *
 * @throws XServerException if find fails due to X-server error
 */
private void findURL(String findCommand, String waitFlag) throws XServerException {
    // build a query string containing all sources that need to be searched
    StringBuilder findBaseString = new StringBuilder();
    for (int i = 0; i < searchSourceIds.size(); i++) {
        findBaseString.append("&find_base_001=" + (String) searchSourceIds.get(i));
    }

    // build URL query string
    StringBuilder query = new StringBuilder(xserverBaseUrl);
    query.append("?op=find_request" + "&wait_flag=" + waitFlag + "&find_request_command=" + findCommand
            + findBaseString.toString() + "&session_id=" + sessionId);

    // connect to URL and get response
    java.io.ByteArrayOutputStream xml = doURLConnection(query.toString());

    if (printXML) {
        // print xml
        LOG.debug(xml.toString());
    }

    // run SAX Parser
    try {
        saxParseXML(new java.io.ByteArrayInputStream(xml.toByteArray()));
    } catch (SAXException sxe) {
        // Error generated by this application
        // (or a parser-initialization error)
        Exception x = sxe;

        if (sxe.getException() != null) {
            x = sxe.getException();
        }

        LOG.warn("findURL() SAX exception: " + sxe.getMessage(), x);
    } catch (IOException ioe) {
        // I/O error
        LOG.warn("findURL() IO exception", ioe);
    }
}

From source file:org.sakaibrary.xserver.XServer.java

/**
 * Gets information on a result set group which has already been created
 * using the find command in asynchronous mode (waitFlag set to "N")
 *
 * @throws XServerException if find_group_info fails due to X-Server error
 *///from w w w  .ja  va2s.com
private void findGroupInfoURL() throws XServerException {
    findResultSets = new java.util.ArrayList();

    StringBuilder query = new StringBuilder(xserverBaseUrl);
    query.append(
            "?op=find_group_info_request" + "&group_number=" + foundGroupNumber + "&session_id=" + sessionId);

    // connect to URL and get response
    java.io.ByteArrayOutputStream xml = doURLConnection(query.toString());

    if (printXML) {
        // print xml
        LOG.debug(xml.toString());
    }

    // run SAX Parser
    try {
        saxParseXML(new java.io.ByteArrayInputStream(xml.toByteArray()));
    } catch (SAXException sxe) {
        // Error generated by this application
        // (or a parser-initialization error)
        Exception x = sxe;

        if (sxe.getException() != null) {
            x = sxe.getException();
        }

        LOG.warn("findGroupInfoURL() SAX exception: " + sxe.getMessage(), x);
    } catch (IOException ioe) {
        // I/O error
        LOG.warn("findGroupInfoURL() IO exception", ioe);
    }
}

From source file:org.sakaibrary.xserver.XServer.java

/**
 * Finds records within the given sources using the given find command
 * query.  Uses the find X-service./*from  w  w w .  java 2 s .  c  om*/
 *
 * @param action valid values: merge, merge_more, remerge, sort_only
 * @param primarySortKey valid values: rank, title, author, year, database
 *
 * @throws XServerException if mergeSort fails due to X-server error
 */
private void mergeSortURL(String action, String primarySortKey) throws XServerException {

    if (primarySortKey == null) {
        // default to rank
        primarySortKey = "rank";
    }

    // build URL query string
    //
    // Limit the number of records fetched to a predefined maximum,
    // XSERVER_RECORDS_TO_FETCH.  This limit applies only to the
    // merge_more and merge_more_set actions - it's ignored for others.
    //
    StringBuilder query = new StringBuilder(xserverBaseUrl);
    query.append("?op=merge_sort_request" + "&group_number=" + foundGroupNumber + "&action=" + action
            + "&primary_sort_key=" + primarySortKey + "&session_id=" + sessionId + "&fetch_more_records="
            + XSERVER_RECORDS_TO_FETCH);

    // connect to URL and get response
    java.io.ByteArrayOutputStream xml = doURLConnection(query.toString());

    if (printXML) {
        // print xml
        LOG.debug(xml.toString());
    }

    // run SAX Parser
    try {
        saxParseXML(new java.io.ByteArrayInputStream(xml.toByteArray()));
    } catch (SAXException sxe) {
        // Error generated by this application
        // (or a parser-initialization error)
        Exception x = sxe;

        if (sxe.getException() != null) {
            x = sxe.getException();
        }

        LOG.warn("mergeSortURL() SAX exception: " + sxe.getMessage(), x);
    } catch (IOException ioe) {
        // I/O error
        LOG.warn("mergeSortURL() IO exception", ioe);
    }
}