Search in sources :

Example 1 with ValidationEventCollector

use of javax.xml.bind.util.ValidationEventCollector in project sldeditor by robward-scisys.

the class ParseXML method parseFile.

/**
 * Parses the xml files, validates against schema and reports any errors.
 *
 * @param resourceFolder the resource folder
 * @param resourceName the resource name
 * @param schemaResource the schema resource
 * @param classToParse the class to parse
 * @return the object
 */
public static Object parseFile(String resourceFolder, String resourceName, String schemaResource, Class<?> classToParse) {
    String fullResourceName = resourceFolder + resourceName;
    logger.debug("Reading : " + fullResourceName);
    InputStream inputStream = ParseXML.class.getResourceAsStream(fullResourceName);
    if (inputStream == null) {
        File file = new File(fullResourceName);
        if (!file.exists()) {
            ConsoleManager.getInstance().error(ParseXML.class, Localisation.getField(ParseXML.class, "ParseXML.failedToFindResource") + fullResourceName);
            return null;
        }
        try {
            inputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            ConsoleManager.getInstance().error(ParseXML.class, Localisation.getField(ParseXML.class, "ParseXML.failedToFindResource") + fullResourceName);
            return null;
        }
    }
    ValidationEventCollector vec = new ValidationEventCollector();
    URL xsdURL = ParseXML.class.getResource(schemaResource);
    try {
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(xsdURL);
        JAXBContext jaxbContext = JAXBContext.newInstance(classToParse);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        jaxbUnmarshaller.setSchema(schema);
        jaxbUnmarshaller.setEventHandler(vec);
        return jaxbUnmarshaller.unmarshal(inputStream);
    } catch (SAXException e) {
        ConsoleManager.getInstance().exception(ParseXML.class, e);
    } catch (javax.xml.bind.UnmarshalException ex) {
        if (vec != null && vec.hasEvents()) {
            for (ValidationEvent ve : vec.getEvents()) {
                String msg = ve.getMessage();
                ValidationEventLocator vel = ve.getLocator();
                String message = String.format("%s %s %s %s %s %d %s %d %s", Localisation.getField(ParseXML.class, "ParseXML.failedToValidate"), fullResourceName, Localisation.getField(ParseXML.class, "ParseXML.usingXSD"), xsdURL.toString(), Localisation.getField(ParseXML.class, "ParseXML.line"), vel.getLineNumber(), Localisation.getField(ParseXML.class, "ParseXML.column"), vel.getColumnNumber(), msg);
                ConsoleManager.getInstance().error(ParseXML.class, message);
            }
        }
    } catch (JAXBException e) {
        ConsoleManager.getInstance().exception(ParseXML.class, e);
    }
    return null;
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Schema(javax.xml.validation.Schema) JAXBException(javax.xml.bind.JAXBException) FileNotFoundException(java.io.FileNotFoundException) JAXBContext(javax.xml.bind.JAXBContext) FileInputStream(java.io.FileInputStream) URL(java.net.URL) SAXException(org.xml.sax.SAXException) ValidationEvent(javax.xml.bind.ValidationEvent) ValidationEventLocator(javax.xml.bind.ValidationEventLocator) Unmarshaller(javax.xml.bind.Unmarshaller) File(java.io.File) ValidationEventCollector(javax.xml.bind.util.ValidationEventCollector)

Example 2 with ValidationEventCollector

use of javax.xml.bind.util.ValidationEventCollector in project TranskribusCore by Transkribus.

the class PageXmlUtils method marshalToBytes.

public static byte[] marshalToBytes(PcGtsType page) throws JAXBException {
    ValidationEventCollector vec = new ValidationEventCollector();
    Marshaller marshaller = createMarshaller(vec);
    ObjectFactory objectFactory = new ObjectFactory();
    JAXBElement<PcGtsType> je = objectFactory.createPcGts(page);
    byte[] data;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        try {
            marshaller.marshal(je, out);
            data = out.toByteArray();
        } finally {
            out.close();
        }
    } catch (Exception e) {
        throw new MarshalException(e);
    }
    String msg = buildMsg(vec, page);
    if (!msg.startsWith(NO_EVENTS_MSG))
        logger.info(msg);
    return data;
}
Also used : Marshaller(javax.xml.bind.Marshaller) MarshalException(javax.xml.bind.MarshalException) TrpObjectFactory(eu.transkribus.core.model.beans.pagecontent_trp.TrpObjectFactory) ObjectFactory(eu.transkribus.core.model.beans.pagecontent.ObjectFactory) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ValidationEventCollector(javax.xml.bind.util.ValidationEventCollector) PcGtsType(eu.transkribus.core.model.beans.pagecontent.PcGtsType) MarshalException(javax.xml.bind.MarshalException) JAXBException(javax.xml.bind.JAXBException) FileNotFoundException(java.io.FileNotFoundException) SAXException(org.xml.sax.SAXException) TransformerException(javax.xml.transform.TransformerException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 3 with ValidationEventCollector

use of javax.xml.bind.util.ValidationEventCollector in project TranskribusCore by Transkribus.

the class PageXmlUtils method marshalToFile.

// public static File marshalToFile(PcGtsType page, File fileOut) throws JAXBException, IOException {
// return marshalToFile(page, fileOut, true);
// }
public static File marshalToFile(PcGtsType page, File fileOut) throws JAXBException, IOException {
    ValidationEventCollector vec = new ValidationEventCollector();
    Marshaller marshaller = createMarshaller(vec);
    ObjectFactory objectFactory = new ObjectFactory();
    JAXBElement<PcGtsType> je = objectFactory.createPcGts(page);
    File backup = null;
    if (fileOut.exists()) {
        logger.debug("file exists: " + fileOut.getAbsolutePath() + " - backing up!");
        backup = CoreUtils.backupFile(fileOut);
    }
    try {
        marshaller.marshal(je, fileOut);
    } catch (Exception e) {
        if (backup != null) {
            logger.debug("restoring backup: " + backup.getAbsolutePath());
            FileUtils.copyFile(backup, fileOut);
        }
        if (e instanceof JAXBException)
            throw e;
        else
            throw new JAXBException(e.getMessage(), e);
    } finally {
        if (backup != null)
            backup.delete();
    }
    String msg = buildMsg(vec, page);
    if (!msg.startsWith(NO_EVENTS_MSG))
        logger.info(msg);
    return fileOut;
}
Also used : Marshaller(javax.xml.bind.Marshaller) TrpObjectFactory(eu.transkribus.core.model.beans.pagecontent_trp.TrpObjectFactory) ObjectFactory(eu.transkribus.core.model.beans.pagecontent.ObjectFactory) JAXBException(javax.xml.bind.JAXBException) ValidationEventCollector(javax.xml.bind.util.ValidationEventCollector) PcGtsType(eu.transkribus.core.model.beans.pagecontent.PcGtsType) File(java.io.File) MarshalException(javax.xml.bind.MarshalException) JAXBException(javax.xml.bind.JAXBException) FileNotFoundException(java.io.FileNotFoundException) SAXException(org.xml.sax.SAXException) TransformerException(javax.xml.transform.TransformerException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 4 with ValidationEventCollector

use of javax.xml.bind.util.ValidationEventCollector in project TranskribusCore by Transkribus.

the class JaxbUtils method marshalToStream.

private static <T> ValidationEvent[] marshalToStream(T object, OutputStream out, boolean doFormatting, MarshallerType type, Class<?>... nestedClasses) throws JAXBException {
    ValidationEventCollector vec = new ValidationEventCollector();
    final Marshaller marshaller;
    // switch(type) {
    // case JSON:
    // marshaller = createJsonMarshaller(object, doFormatting, nestedClasses);
    // break;
    // default:
    // marshaller = createXmlMarshaller(object, doFormatting, nestedClasses);
    // break;
    // }
    marshaller = createXmlMarshaller(object, doFormatting, nestedClasses);
    marshaller.setEventHandler(vec);
    marshaller.marshal(object, out);
    checkEvents(vec);
    return vec.getEvents();
}
Also used : Marshaller(javax.xml.bind.Marshaller) ValidationEventCollector(javax.xml.bind.util.ValidationEventCollector)

Example 5 with ValidationEventCollector

use of javax.xml.bind.util.ValidationEventCollector in project Payara by payara.

the class AppClientFacade method readConfig.

private static ClientContainer readConfig(final String configPath, final ClassLoader loader) throws UserError, JAXBException, FileNotFoundException, ParserConfigurationException, SAXException, URISyntaxException, IOException {
    ClientContainer result = null;
    Reader configReader = null;
    String configFileLocationForErrorMessage = "";
    try {
        /*
             * During a Java Web Start launch, the config is passed as a property
             * value.
             */
        String configInProperty = System.getProperty(ACC_CONFIG_CONTENT_PROPERTY_NAME);
        if (configInProperty != null) {
            /*
                 * Awkwardly, the glassfish-acc.xml content refers to a config file.
                 * We work around this for Java Web Start launch by capturing the
                 * content of that config file into a property setting in the
                 * generated JNLP document.  We need to write that content into
                 * a temporary file here on the client and then replace a
                 * placeholder in the glassfish-acc.xml content with the path to that
                 * temp file.
                 */
            final File securityConfigTempFile = Util.writeTextToTempFile(configInProperty, "wss-client-config", ".xml", false);
            final Properties p = new Properties();
            p.setProperty("security.config.path", securityConfigTempFile.getAbsolutePath());
            configInProperty = Util.replaceTokens(configInProperty, p);
            configReader = new StringReader(configInProperty);
        } else {
            /*
                 * This is not a Java Web Start launch, so read the configuration
                 * from a disk file.
                 */
            File configFile = checkXMLFile(configPath);
            checkXMLFile(appClientCommandArgs.getConfigFilePath());
            configReader = new FileReader(configFile);
            configFileLocationForErrorMessage = configFile.getAbsolutePath();
        }
        /*
             * Although JAXB makes it very simple to parse the XML into Java objects,
             * we have to do several things explicitly to use our local copies of
             * DTDs and XSDs.
             */
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setValidating(true);
        spf.setNamespaceAware(true);
        SAXParser parser = spf.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        /*
             * Get the local entity resolver that knows about the
             * bundled .dtd and .xsd files.
             */
        reader.setEntityResolver(new SaxParserHandlerBundled());
        /*
             * To support installation-directory independence the default glassfish-acc.xml
             * refers to the wss-config file using ${com.sun.aas.installRoot}...  So
             * preprocess the glassfish-acc.xml file to replace any tokens with the
             * corresponding values, then submit that result to JAXB.
             */
        InputSource inputSource = replaceTokensForParsing(configReader);
        SAXSource saxSource = new SAXSource(reader, inputSource);
        JAXBContext jc = JAXBContext.newInstance(ClientContainer.class);
        final ValidationEventCollector vec = new ValidationEventCollector();
        Unmarshaller u = jc.createUnmarshaller();
        u.setEventHandler(vec);
        result = (ClientContainer) u.unmarshal(saxSource);
        if (vec.hasEvents()) {
            /*
                 * The parser reported at least one warning or error.  If all
                 * events were warnings, display them as a message and continue.
                 * Otherwise there was at least one error or fatal, so say so
                 * and try to continue but say that such errors might be fatal
                 * in future releases.
                 */
            boolean isError = false;
            final StringBuilder sb = new StringBuilder();
            for (ValidationEvent ve : vec.getEvents()) {
                sb.append(ve.getMessage()).append(LINE_SEP);
                isError |= (ve.getSeverity() != ValidationEvent.WARNING);
            }
            final String messageIntroduction = localStrings.getLocalString(AppClientFacade.class, isError ? "appclient.errParsingConfig" : "appclient.warnParsingConfig", isError ? "Error parsing app client container configuration {0}.  Attempting to continue.  In future releases such parsing errors might become fatal.  Please correct your configuration file." : "Warning(s) parsing app client container configuration {0}.  Continuing.", new Object[] { configFileLocationForErrorMessage });
            /*
                 * Following code - which throws an exception if the config
                 * validation fails - is commented out to prevent possible
                 * regressions.  Users might have customized the acc config file
                 * in a way that does not validate but would have worked silently
                 * before.
                 */
            // if (isErrorOrWorse) {
            // throw new UserError(messageIntroduction,
            // new ValidationException(sb.toString()));
            // } else {
            System.err.println(messageIntroduction + LINE_SEP + sb.toString());
        // }
        }
        return result;
    } finally {
        if (configReader != null) {
            configReader.close();
        }
    }
}
Also used : InputSource(org.xml.sax.InputSource) ClientContainer(org.glassfish.appclient.client.acc.config.ClientContainer) AppClientContainer(org.glassfish.appclient.client.acc.AppClientContainer) Reader(java.io.Reader) XMLReader(org.xml.sax.XMLReader) InputStreamReader(java.io.InputStreamReader) StringReader(java.io.StringReader) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) Properties(java.util.Properties) SaxParserHandlerBundled(com.sun.enterprise.deployment.node.SaxParserHandlerBundled) SAXSource(javax.xml.transform.sax.SAXSource) StringReader(java.io.StringReader) SAXParser(javax.xml.parsers.SAXParser) FileReader(java.io.FileReader) File(java.io.File) ValidationEventCollector(javax.xml.bind.util.ValidationEventCollector) XMLReader(org.xml.sax.XMLReader) SAXParserFactory(javax.xml.parsers.SAXParserFactory)

Aggregations

ValidationEventCollector (javax.xml.bind.util.ValidationEventCollector)5 File (java.io.File)3 FileNotFoundException (java.io.FileNotFoundException)3 JAXBException (javax.xml.bind.JAXBException)3 Marshaller (javax.xml.bind.Marshaller)3 SAXException (org.xml.sax.SAXException)3 ObjectFactory (eu.transkribus.core.model.beans.pagecontent.ObjectFactory)2 PcGtsType (eu.transkribus.core.model.beans.pagecontent.PcGtsType)2 TrpObjectFactory (eu.transkribus.core.model.beans.pagecontent_trp.TrpObjectFactory)2 IOException (java.io.IOException)2 MarshalException (javax.xml.bind.MarshalException)2 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)2 TransformerException (javax.xml.transform.TransformerException)2 SaxParserHandlerBundled (com.sun.enterprise.deployment.node.SaxParserHandlerBundled)1 BufferedReader (java.io.BufferedReader)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 FileInputStream (java.io.FileInputStream)1 FileReader (java.io.FileReader)1 InputStream (java.io.InputStream)1 InputStreamReader (java.io.InputStreamReader)1