private static String marshallToString(Object object, boolean includeXMLHeader) throws MarshalException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream( 100); try { JAXBContext context = JAXBContext.newInstance(object.getClass()); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, !includeXMLHeader); marshaller.marshal(object, byteArrayOutputStream); return new String(byteArrayOutputStream.toByteArray()); } catch (Throwable e) { throw new MarshalException("Unable to marshal object to stream", e); } finally { IOUtils.closeQuietly(byteArrayOutputStream); } }
/** * Convert the given {@code JAXBException} to an appropriate exception from the * {@code org.springframework.oxm} hierarchy. * @param ex {@code JAXBException} that occured * @return the corresponding {@code XmlMappingException} */ protected XmlMappingException convertJaxbException(JAXBException ex) { if (ex instanceof ValidationException) { return new ValidationFailureException("JAXB validation exception", ex); } else if (ex instanceof MarshalException) { return new MarshallingFailureException("JAXB marshalling exception", ex); } else if (ex instanceof UnmarshalException) { return new UnmarshallingFailureException("JAXB unmarshalling exception", ex); } else { // fallback return new UncategorizedMappingException("Unknown JAXB exception", ex); } }
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; }
public static <T> byte[] marshalToBytes(T object, Class<?>... nestedClasses) throws JAXBException { byte[] data; ByteArrayOutputStream out = new ByteArrayOutputStream(); try{ try{ marshalToStream(object, out, nestedClasses); data = out.toByteArray(); } finally { out.close(); } } catch (Exception e){ throw new MarshalException(e); } return data; }
/** * Turns an individual JAXB element into an XML fragment string using the given validation mode. * * @throws MarshalException if schema validation failed */ public String marshal(JAXBElement<?> element, ValidationMode validationMode) throws MarshalException { os.reset(); marshaller.setSchema((validationMode == STRICT) ? schema : null); try { marshaller.marshal(element, os); } catch (JAXBException e) { throwIfInstanceOf(e, MarshalException.class); throw new RuntimeException("Mysterious XML exception", e); } String fragment = new String(os.toByteArray(), UTF_8); int endOfFirstLine = fragment.indexOf(">\n"); verify(endOfFirstLine > 0, "Bad XML fragment:\n%s", fragment); String firstLine = fragment.substring(0, endOfFirstLine + 2); String rest = fragment.substring(firstLine.length()); return XMLNS_PATTERN.matcher(firstLine).replaceAll("") + rest; }
/** * Attempt to get the most informative detail from the given exception * @param e Exception to dig * @return Detail String */ protected String getDetail(final Exception e) { if (e == null) return null; if (e instanceof ValidationException || e instanceof MarshalException) { Throwable t = e.getCause(); if (t != null) { while (t.getCause() != null) { t = t.getCause(); } return t.getMessage(); } } if (e instanceof IllegalArgumentException) { return "Unable to parse XML: " + e.getMessage(); } return e.getMessage(); }
/** * @see javax.xml.bind.annotation.adapters.XmlAdapter#marshal(java.lang.Object) */ @Override public NameAndNamespacePair marshal(NameAndNamespacePair v) throws Exception { if (v != null) { if (StringUtils.isBlank(v.getName())) { throw new MarshalException("Cannot export a name-and-namespace pair with a blank name"); } else if (StringUtils.isBlank(v.getNamespaceCode())) { throw new MarshalException("Cannot export a name-and-namespace pair with a blank namespace code"); } else if (CoreServiceApiServiceLocator.getNamespaceService().getNamespace(v.getNamespaceCode()) == null) { throw new MarshalException("Cannot export a name-and-namespace pair with invalid or unknown namespace \"" + v.getNamespaceCode() + "\""); } v.setName(new NormalizedStringAdapter().marshal(v.getName())); v.setNamespaceCode(v.getNamespaceCode()); } return v; }
private void write( XMLSerializable obj, ContentHandler writer ) throws JAXBException { try { if( getSchemaLocation()!=null || getNoNSSchemaLocation()!=null ) { // if we need to add xsi:schemaLocation or its brother, // throw in the component to do that. writer = new SchemaLocationFilter( getSchemaLocation(), getNoNSSchemaLocation(), writer ); } SAXMarshaller serializer = new SAXMarshaller(writer,prefixMapper,this); // set a DocumentLocator that doesn't provide any information writer.setDocumentLocator( new LocatorImpl() ); writer.startDocument(); serializer.childAsBody(obj,null); writer.endDocument(); serializer.reconcileID(); // extra check } catch( SAXException e ) { throw new MarshalException(e); } }
private OnWire _adaptM(XMLSerializer serializer, InMemory v) throws MarshalException { XmlAdapter<OnWire,InMemory> a = serializer.getAdapter(adapter); try { return a.marshal(v); } catch (Exception e) { serializer.handleError(e,v,null); throw new MarshalException(e); } }
void marshal(InMemory o, XMLSerializer out) throws IOException, SAXException, XMLStreamException { try { core.marshal(_adaptM( XMLSerializer.getInstance(), o ), out ); } catch (MarshalException e) { // recover from error by not marshalling this element. } }
@Test public void testMarshalError() throws JAXBException { try { MarshalHelper.marshalError(car); fail("no exception thrown"); } catch (MarshalException e) { logger.error("MarshalException", e); assertTrue(e.toString() .contains("is missing an @XmlRootElement annotation")); } }
/** * Turns XJC element into XML fragment, converting {@link MarshalException}s to {@link * RuntimeException}s. */ public String marshalOrDie(JAXBElement<?> element) { try { return marshal(element); } catch (MarshalException e) { throw new RuntimeException(e); } }
private DepositFragment marshalResource( RdeResourceType type, ImmutableObject resource, JAXBElement<?> element) { String xml = ""; String error = ""; try { xml = marshal(element); } catch (MarshalException e) { error = String.format("RDE XML schema validation failed: %s\n%s%s\n", Key.create(resource), e.getLinkedException(), getMarshaller().marshalLenient(element)); logger.severe(e, error); } return DepositFragment.create(type, xml, error); }
/** Turns an individual JAXB element into an XML fragment string. */ public String marshalLenient(JAXBElement<?> element) { try { return marshal(element, LENIENT); } catch (MarshalException e) { throw new RuntimeException("MarshalException shouldn't be thrown in lenient mode", e); } }
/** * @see javax.xml.bind.annotation.adapters.XmlAdapter#marshal(java.lang.Object) */ @Override public NameAndNamespacePair marshal(String v) throws Exception { if (v != null) { Template permissionTemplate = KimApiServiceLocator.getPermissionService().getPermissionTemplate(v); if (permissionTemplate == null) { throw new MarshalException("Cannot find permission template with ID \"" + v + "\""); } return new NameAndNamespacePair(permissionTemplate.getNamespaceCode(), permissionTemplate.getName()); } return null; }
/** * @see javax.xml.bind.annotation.adapters.XmlAdapter#marshal(java.lang.Object) */ @Override public NameAndNamespacePair marshal(String v) throws Exception { if (v != null) { KimTypeContract kimType = KimApiServiceLocator.getKimTypeInfoService().getKimType(StringUtils.trim(v)); if (kimType == null) { throw new MarshalException("Cannot find KIM Type with ID \"" + v + "\""); } return new NameAndNamespacePair(kimType.getNamespaceCode(), kimType.getName()); } return null; }
public XmlOutput createWriter( OutputStream os, String encoding ) throws JAXBException { // UTF8XmlOutput does buffering on its own, and // otherwise createWriter(Writer) inserts a buffering, // so no point in doing a buffering here. if(encoding.equals("UTF-8")) { Encoded[] table = context.getUTF8NameTable(); final UTF8XmlOutput out; if(isFormattedOutput()) out = new IndentingUTF8XmlOutput(os, indent, table, escapeHandler); else { if(c14nSupport) out = new C14nXmlOutput(os, table, context.c14nSupport, escapeHandler); else out = new UTF8XmlOutput(os, table, escapeHandler); } if(header!=null) out.setHeader(header); return out; } try { return createWriter( new OutputStreamWriter(os,getJavaEncoding(encoding)), encoding ); } catch( UnsupportedEncodingException e ) { throw new MarshalException( Messages.UNSUPPORTED_ENCODING.format(encoding), e ); } }
@Test(expected = MarshalException.class) public void generatesAndUsesSchema() throws JAXBException, IOException, SAXException { final JAXBContext context = JAXBContext.newInstance(A.class); final DOMResult result = new DOMResult(); result.setSystemId("schema.xsd"); context.generateSchema(new SchemaOutputResolver() { @Override public Result createOutput(String namespaceUri, String suggestedFileName) { return result; } }); @SuppressWarnings("deprecation") final SchemaFactory schemaFactory = SchemaFactory .newInstance(WellKnownNamespace.XML_SCHEMA); final Schema schema = schemaFactory.newSchema(new DOMSource(result .getNode())); final Marshaller marshaller = context.createMarshaller(); marshaller.setSchema(schema); // Works marshaller.marshal(new A("works"), System.out); // Fails marshaller.marshal(new A(null), System.out); }
@Test public void testMarshalError() throws JAXBException { try { MarshalHelper.marshalError(car); fail("no exception thrown"); } catch (MarshalException e) { logger.error("MarshalException", e); assertTrue(e.toString().contains( "is missing an @XmlRootElement annotation")); } }
@OverrideOnDemand protected void handleWriteException (@Nonnull final JAXBException ex) { if (ex instanceof MarshalException) s_aLogger.error ("Marshal exception writing object", ex); else s_aLogger.warn ("JAXB Exception writing object", ex); }
public void onException (@Nonnull final JAXBException ex) { if (ex instanceof MarshalException) s_aLogger.error ("Marshal exception writing object", ex); else s_aLogger.warn ("JAXB Exception writing object", ex); }