javax.xml.bind.util.ValidationEventCollector Java Examples

The following examples show how to use javax.xml.bind.util.ValidationEventCollector. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PageXmlUtils.java    From TranskribusCore with GNU General Public License v3.0 6 votes vote down vote up
public static Unmarshaller createUnmarshaller(ValidationEventCollector vec) throws JAXBException {
	JAXBContext jc = createPageJAXBContext();

	Unmarshaller u = jc.createUnmarshaller();
	try {
		u.setProperty("com.sun.xml.internal.bind.ObjectFactory", new TrpObjectFactory());
	} catch(PropertyException pe) {
		u.setProperty("com.sun.xml.bind.ObjectFactory", new TrpObjectFactory());
	}
	u.setListener(new TrpPageUnmarshalListener());

	if(vec != null) {
		u.setEventHandler(vec);
	}
	
	return u;
}
 
Example #2
Source File: PageXmlUtils.java    From TranskribusCore with GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #3
Source File: JaxbUtils.java    From TranskribusCore with GNU General Public License v3.0 6 votes vote down vote up
/**
	 * Marshal object to stream.
	 * 
	 * FIXME
	 * This method support JSON, but the representation does not match the one produced and accepted by Jersey! See {@link ExportParameters}Test
	 * 
	 * @param object
	 * @param out
	 * @param doFormatting
	 * @param type
	 * @param nestedClasses
	 * @return
	 * @throws JAXBException
	 */
	private static <T> ValidationEvent[] marshalToStream(T object, OutputStream out, 
			boolean doFormatting, MarshallerType type, Class<?>... nestedClasses) throws JAXBException {
		ValidationEventCollector vec = new ValidationEventCollector();

		if(type == null) {
			type = MarshallerType.XML;
		}
		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();
	}
 
Example #4
Source File: PcGtsTypeMessageBodyReaderTest.java    From TranskribusCore with GNU General Public License v3.0 6 votes vote down vote up
public void testDamagedXml() throws FileNotFoundException, IOException, JAXBException {
		File f = new File("/media/daten/Dokumente/Bentham_batch2_test/page/116_630_001.xml");
		
//		PcGtsTypeMessageBodyReader reader = new PcGtsTypeMessageBodyReader();
//		
//		reader.readFrom(type, genericType, annotations, mediaType, httpHeaders, entityStream)
		try(FileInputStream stream = new FileInputStream(f)) {
			
			ValidationEventCollector vec = new ValidationEventCollector();
			PcGtsType pc =  PageXmlUtils.unmarshal(stream, vec);
			
			for(ValidationEvent e : vec.getEvents()) {
				logger.info("Has validation event with severity: " + e.getSeverity());
			}
			
//			List<TextLineType> lines = PageXmlUtils.getLines(pc);
//			logger.info("has lines: " + lines.size());
//			for(TextLineType l : lines) {
//				logger.debug(l.getId());
//			}
		}
		
		
	}
 
Example #5
Source File: ParseXML.java    From sldeditor with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Output parse errors.
 *
 * @param fullResourceName the full resource name
 * @param vec the vec
 * @param xsdURL the xsd URL
 */
private static void outputParseErrors(
        String fullResourceName, ValidationEventCollector vec, URL xsdURL) {
    if (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);
        }
    }
}
 
Example #6
Source File: WorkflowProfiles.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
private Unmarshaller getUnmarshaller() throws JAXBException {
    JAXBContext jctx = JAXBContext.newInstance(WorkflowDefinition.class);
    Unmarshaller unmarshaller = jctx.createUnmarshaller();
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL schemaUrl = WorkflowDefinition.class.getResource("workflow.xsd");
    Schema schema = null;
    try {
        schema = sf.newSchema(new StreamSource(schemaUrl.toExternalForm()));
    } catch (SAXException ex) {
        throw new JAXBException("Missing schema workflow.xsd!", ex);
    }
    unmarshaller.setSchema(schema);
    ValidationEventCollector errors = new ValidationEventCollector() {

        @Override
        public boolean handleEvent(ValidationEvent event) {
            super.handleEvent(event);
            return true;
        }

    };
    unmarshaller.setEventHandler(errors);
    return unmarshaller;
}
 
Example #7
Source File: PageXmlUtils.java    From TranskribusCore with GNU General Public License v3.0 5 votes vote down vote up
private static Marshaller createMarshaller(ValidationEventCollector vec) throws JAXBException {
	JAXBContext jc = createPageJAXBContext();
	Marshaller m = jc.createMarshaller();
	m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
	m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
	m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, schemaLocStr);
	m.setEventHandler(vec);
	m.setListener(new TrpPageMarshalListener());
	
	return m;
}
 
Example #8
Source File: PageXmlUtils.java    From TranskribusCore with GNU General Public License v3.0 5 votes vote down vote up
public static PcGtsType unmarshal(InputStream is, ValidationEventCollector vec) throws JAXBException {
	Unmarshaller u = createUnmarshaller(vec);

	@SuppressWarnings("unchecked")
	PcGtsType pageData = ((JAXBElement<PcGtsType>) u.unmarshal(is)).getValue();
	onPostConstruct(pageData);
	
	return pageData;
}
 
Example #9
Source File: PageXmlUtils.java    From TranskribusCore with GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example #10
Source File: PageXmlUtils.java    From TranskribusCore with GNU General Public License v3.0 5 votes vote down vote up
private static String buildMsg(ValidationEventCollector vec, PcGtsType page) {
	String imgFn = "";
	if (page.getPage()!=null) {
		imgFn = page.getPage().getImageFilename();
	}
	
	String msg;
	if (vec.hasEvents()) {
		msg="Events occured while marshalling xml file: " + vec.getEvents().length;
	} else {
		msg=NO_EVENTS_MSG;
	}
	if (!imgFn.isEmpty()) msg += " (img: "+imgFn+")";
	return msg;
}
 
Example #11
Source File: JaxbUtils.java    From TranskribusCore with GNU General Public License v3.0 5 votes vote down vote up
private static void checkEvents(ValidationEventCollector vec) {
	if (vec.hasEvents()) {
		logger.info("Events occured while marshalling xml file: " + vec.getEvents().length);
		ValidationEvent[] events = vec.getEvents();
		for(ValidationEvent e : events){
			logger.info(e.getMessage());
		}
	} else {
		logger.debug("No events occured during marshalling xml file!");
	}
}
 
Example #12
Source File: WorkflowProfiles.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
private void read() throws JAXBException {
    long currentTime = file.lastModified();
    if (currentTime == lastModified) {
        return ;
    }
    Unmarshaller unmarshaller = getUnmarshaller();
    ValidationEventCollector errors = (ValidationEventCollector) unmarshaller.getEventHandler();
    WorkflowDefinition fetchedWf = null;
    try {
        WorkflowDefinition wf = (WorkflowDefinition) unmarshaller.unmarshal(file);
        if (!errors.hasEvents()) {
            readCaches(wf);
            fetchedWf = wf;
        }
    } catch (UnmarshalException ex) {
        if (!errors.hasEvents()) {
            throw ex;
        }
    } finally {
        setProfiles(fetchedWf, currentTime);
    }
    if (errors.hasEvents()) {
        StringBuilder err = new StringBuilder();
        for (ValidationEvent event : errors.getEvents()) {
            err.append(event).append('\n');
        }
        throw new JAXBException(err.toString());
    }
}
 
Example #13
Source File: XMLUnMarshaller.java    From cougar with Apache License 2.0 5 votes vote down vote up
private void validate(ValidationEventCollector handler)
		throws ValidationException {
	if(handler.hasEvents()) {
		ValidationEvent[] events = handler.getEvents();
		StringBuilder sb = new StringBuilder();
		for(ValidationEvent event : events) {
			sb.append(event.getMessage());
		}
		throw new ValidationException(sb.toString());
	}
}
 
Example #14
Source File: PageXmlUtils.java    From TranskribusCore with GNU General Public License v3.0 4 votes vote down vote up
private static Marshaller createMarshaller() throws JAXBException {
	return createMarshaller(new ValidationEventCollector());
}