javax.xml.bind.MarshalException Java Examples

The following examples show how to use javax.xml.bind.MarshalException. 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: Jaxb2Marshaller.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Convert the given {@code JAXBException} to an appropriate exception
 * from the {@code org.springframework.oxm} hierarchy.
 * @param ex {@code JAXBException} that occurred
 * @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);
	}
}
 
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: Jaxb2Marshaller.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example #4
Source File: JaxbUtils.java    From TranskribusCore with GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #5
Source File: XmlFragmentMarshaller.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #6
Source File: JaxbUtilTest.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Test
public void marshallingProducesNonJaxbException() {
    final KeyDataConfig input =
            new KeyDataConfig(new PrivateKeyData("VAL", null, null, null, null), PrivateKeyType.UNLOCKED);

    IOException exception = new IOException("What you talking about willis?");

    OutputStream out =
            mock(
                    OutputStream.class,
                    (iom) -> {
                        throw exception;
                    });
    final Throwable throwable = catchThrowable(() -> JaxbUtil.marshal(input, out));

    assertThat(throwable)
            .isInstanceOf(ConfigException.class)
            .hasCauseExactlyInstanceOf(javax.xml.bind.MarshalException.class);
}
 
Example #7
Source File: NameAndNamespacePairValidatingAdapter.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @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;
}
 
Example #8
Source File: NameAndNamespacePairValidatingAdapter.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * @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;
}
 
Example #9
Source File: Jaxb2Marshaller.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Convert the given {@code JAXBException} to an appropriate exception from the
 * {@code org.springframework.oxm} hierarchy.
 * @param ex {@code JAXBException} that occurred
 * @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);
	}
}
 
Example #10
Source File: NameAndNamespacePairToPermTemplateIdAdapter.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * @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;
}
 
Example #11
Source File: NameAndNamespacePairToKimTypeIdAdapter.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * @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;
}
 
Example #12
Source File: NameAndNamespacePairToKimTypeIdAdapter.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @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;
}
 
Example #13
Source File: NameAndNamespacePairToPermTemplateIdAdapter.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @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;
}
 
Example #14
Source File: LoggingJAXBWriteExceptionHandler.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
public void onException (@Nonnull final JAXBException ex)
{
  if (ex instanceof MarshalException)
    LOGGER.error ("Marshal exception writing object", ex);
  else
    LOGGER.warn ("JAXB Exception writing object", ex);
}
 
Example #15
Source File: DynamicSchemaTest.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@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);
}
 
Example #16
Source File: XmlFragmentMarshaller.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/** 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);
  }
}
 
Example #17
Source File: RdeMarshaller.java    From nomulus with Apache License 2.0 5 votes vote down vote up
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.atSevere().withCause(e).log(error);
  }
  return DepositFragment.create(type, xml, error);
}
 
Example #18
Source File: RdeMarshaller.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example #19
Source File: BridgeAdapter.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
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.
    }
}
 
Example #20
Source File: BridgeAdapter.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example #21
Source File: DataWriterImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void onCompleteMarshalling() {
    if (setEventHandler && veventHandler instanceof MarshallerEventHandler) {
        try {
            ((MarshallerEventHandler) veventHandler).onMarshalComplete();
        } catch (MarshalException e) {
            if (e.getLinkedException() != null) {
                throw new Fault(new Message("MARSHAL_ERROR", LOG,
                        e.getLinkedException().getMessage()), e);
            }
            throw new Fault(new Message("MARSHAL_ERROR", LOG, e.getMessage()), e);
        }
    }
}
 
Example #22
Source File: MyCustomMarshallerHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void onMarshalComplete() throws MarshalException {
    this.onMarshalComplete = true;

    if (hasEvents()) {
        throw new MarshalException("My marshalling exception");
    }
}
 
Example #23
Source File: BridgeAdapter.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
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.
    }
}
 
Example #24
Source File: BridgeAdapter.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example #25
Source File: BridgeAdapter.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
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.
    }
}
 
Example #26
Source File: BridgeAdapter.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example #27
Source File: BridgeAdapter.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
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.
    }
}
 
Example #28
Source File: JaxbUtilTest.java    From tessera with Apache License 2.0 5 votes vote down vote up
@Test
public void marshallingProducesError() {
    final Exception ex = new Exception();

    OutputStream out = mock(OutputStream.class);
    final Throwable throwable = catchThrowable(() -> JaxbUtil.marshal(ex, out));

    assertThat(throwable).isInstanceOf(ConfigException.class).hasCauseExactlyInstanceOf(MarshalException.class);
}
 
Example #29
Source File: JaxbUtilTest.java    From tessera with Apache License 2.0 5 votes vote down vote up
@Test
public void marshallingNOValidationProducesError() {
    final Exception ex = new Exception();

    OutputStream out = mock(OutputStream.class);
    final Throwable throwable = catchThrowable(() -> JaxbUtil.marshalWithNoValidation(ex, out));

    assertThat(throwable).isInstanceOf(ConfigException.class).hasCauseExactlyInstanceOf(MarshalException.class);
}
 
Example #30
Source File: RuleToXmlConverterTest.java    From yare with MIT License 5 votes vote down vote up
@Test
void shouldNotMarshallRuleInconsistentWithSchema() {
    // given
    Rule ruleObject = TestRuleFactory.constructInvalidRule();
    // when
    assertThatThrownBy(() -> converter.marshal(ruleObject))
            // then
            .isInstanceOf(RuleConversionException.class).hasCauseExactlyInstanceOf(MarshalException.class);
}