org.eclipse.persistence.jaxb.MarshallerProperties Java Examples

The following examples show how to use org.eclipse.persistence.jaxb.MarshallerProperties. 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: JerseyValidationTest.java    From parsec-libraries with Apache License 2.0 6 votes vote down vote up
@Override
protected Application configure() {
    //enable(TestProperties.LOG_TRAFFIC);
    //enable(TestProperties.DUMP_ENTITY);
    //
    // TODO: load web.xml directly
    // .property(
    //        "contextConfigLocation",
    //        "classpath:**/my-web-test-context.xml"
    //
    return new ResourceConfig(MyResource.class)
            .register(ParsecMoxyProvider.class)
            .register(JaxbExceptionMapper.class)
            .property(JaxbExceptionMapper.PROP_JAXB_DEFAULT_ERROR_CODE, JAXB_ERROR_CODE)
            .property(JaxbExceptionMapper.PROP_JAXB_DEFAULT_ERROR_MSG, JAXB_ERROR_MSG)
            .register(ValidationConfigurationContextResolver.class)
            .register(ParsecValidationExceptionMapper.class)
            .property(ParsecValidationExceptionMapper.PROP_VALIDATION_DEFAULT_ERROR_CODE, VALIDATION_ERROR_CODE)
            .property(ParsecValidationExceptionMapper.PROP_VALIDATION_DEFAULT_ERROR_MSG, VALIDATION_ERROR_MSG)
            .property(ServerProperties.METAINF_SERVICES_LOOKUP_DISABLE, true)
            .register(new MoxyJsonConfig().setFormattedOutput(true)
                    .property(MarshallerProperties.BEAN_VALIDATION_MODE, BeanValidationMode.NONE).resolver());

}
 
Example #2
Source File: XMLConvertor.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void initialize(String schema) throws JAXBException {

		um = context.createUnmarshaller();
		um.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/xml");
	
		m = context.createMarshaller();
		m.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
		m.setProperty("com.sun.xml.internal.bind.namespacePrefixMapper",
				new NamespacePrefixMapper() {
					@Override
					public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) {
						if(namespaceUri.equals(WellKnownNamespace.XML_SCHEMA_INSTANCE)) {
							return "xsi";
						} else 
							return "m2m";
					}
				});
		String schemaLocation = schema;

		if(schemaLocation != null) {
			m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://www.onem2m.org/xml/protocols " + schemaLocation);
		}
		m.setProperty(MarshallerProperties.MEDIA_TYPE, "application/xml");
	}
 
Example #3
Source File: XmlHelper.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * Returns XML representation of the object using the herd custom character escape handler.
 *
 * @param obj the Java object to be serialized
 * @param formatted specifies whether or not the marshalled XML data is formatted with line feeds and indentation
 *
 * @return the XML representation of this object
 * @throws JAXBException if a JAXB error occurred.
 */
public String objectToXml(Object obj, boolean formatted) throws JAXBException
{
    JAXBContext requestContext = JAXBContext.newInstance(obj.getClass());
    Marshaller requestMarshaller = requestContext.createMarshaller();

    if (formatted)
    {
        requestMarshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.name());
        requestMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    }

    // Specify a custom character escape handler to escape XML 1.1 restricted characters.
    requestMarshaller.setProperty(MarshallerProperties.CHARACTER_ESCAPE_HANDLER, herdCharacterEscapeHandler);

    StringWriter sw = new StringWriter();
    requestMarshaller.marshal(obj, sw);

    return sw.toString();
}
 
Example #4
Source File: RestSpringModuleConfig.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * Gets a new JAXB marshaller that is aware of our XSD and can perform schema validation. It is also aware of all our auto-generated classes that are in the
 * org.finra.herd.model.api.xml package. Note that REST endpoints that use Java objects which are not in this package will not use this marshaller and will
 * not get schema validated which is good since they don't have an XSD.
 *
 * @return the newly created JAXB marshaller.
 */
@Bean
public Jaxb2Marshaller jaxb2Marshaller()
{
    try
    {
        // Create the marshaller that is aware of our Java XSD and it's auto-generated classes.
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setPackagesToScan("org.finra.herd.model.api.xml");
        marshaller.setSchemas(resourceResolver.getResources("classpath:herd.xsd"));

        // Get the JAXB XML headers from the environment.
        String xmlHeaders = configurationHelper.getProperty(ConfigurationValue.JAXB_XML_HEADERS);

        // We need to set marshaller properties to reconfigure the XML header.
        Map<String, Object> marshallerProperties = new HashMap<>();
        marshaller.setMarshallerProperties(marshallerProperties);

        // Remove the header that JAXB will generate.
        marshallerProperties.put(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

        // Specify the new XML headers.
        marshallerProperties.put(ConfigurationValue.JAXB_XML_HEADERS.getKey(), xmlHeaders);

        // Specify a custom character escape handler to escape XML 1.1 restricted characters.
        marshallerProperties.put(MarshallerProperties.CHARACTER_ESCAPE_HANDLER, herdCharacterEscapeHandler);

        // Return the marshaller.
        return marshaller;
    }
    catch (Exception ex)
    {
        // Throw a runtime exception instead of a checked IOException since the XSD file should be contained within our application.
        throw new IllegalArgumentException("Unable to create marshaller.", ex);
    }
}
 
Example #5
Source File: XMLConvertor.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void initialize(String schema) throws JAXBException {

		um = context.createUnmarshaller();
		um.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/xml");
	
		m = context.createMarshaller();
		m.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
		m.setProperty("com.sun.xml.internal.bind.namespacePrefixMapper",
				new NamespacePrefixMapper() {
					@Override
					public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) {
						if(namespaceUri.equals(WellKnownNamespace.XML_SCHEMA_INSTANCE)) {
							return "xsi";
						} else 
							return "m2m";
					}
				});
		String schemaLocation = schema;

		if(schemaLocation != null) {
			m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://www.onem2m.org/xml/protocols " + schemaLocation);
		}
		m.setProperty(MarshallerProperties.MEDIA_TYPE, "application/xml");
	}
 
Example #6
Source File: JAXBWriter.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
private Marshaller createJsonMarshaller() {
    try {
        Marshaller marshaller;
        marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, StringUtil.ENCODING_UTF8);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
        marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);
        return marshaller;
    } catch (JAXBException e) {
        throw new RuntimeException(e);
    }
}
 
Example #7
Source File: XmlTransformer.java    From recheck with GNU Affero General Public License v3.0 5 votes vote down vote up
public void toXML( final Object obj, final OutputStream out, final Marshaller.Listener listener ) {
	Marshaller marshaller = null;
	try {
		final JAXBContext jc = createJAXBContext( additionalClazzes );
		marshaller = jc.createMarshaller();
		marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );
		marshaller.setProperty( MarshallerProperties.NAMESPACE_PREFIX_MAPPER,
				new MapNamespacePrefixMapper( NAMESPACE_MAPPINGS ) );
		marshaller.setProperty( MarshallerProperties.INDENT_STRING, "\t" );
		marshaller.setEventHandler( new DefaultValidationEventHandler() );
		marshaller.setListener( listener );
		final SessionLogDelegate sessionLog = new SessionLogDelegate( AbstractSessionLog.getLog() );
		AbstractSessionLog.setLog( sessionLog );

		if ( config.isOnlyFragment() ) {
			log.info( "Create only fragment for '{}'.", obj );
			marshaller.setProperty( Marshaller.JAXB_FRAGMENT, true );
		}

		if ( config.isLightweightXml() ) {
			log.info( "Use lightweight XML for '{}'.", obj );
			lightweightMarshallerSet.add( marshaller );
			XmlUtil.addLightWeightAdapter( marshaller );
		}

		marshaller.marshal( obj, out );

		if ( sessionLog.containsMessages() ) {
			throw new RuntimeException( "Error persisting XML: " + sessionLog.getLog() );
		}
	} catch ( final JAXBException e ) {
		throw new RuntimeException( e );
	} finally {
		if ( config.isLightweightXml() && marshaller != null ) {
			lightweightMarshallerSet.remove( marshaller );
		}
	}
}
 
Example #8
Source File: JAXBWriter.java    From airsonic with GNU General Public License v3.0 5 votes vote down vote up
private Marshaller createJsonMarshaller() {
    try {
        Marshaller marshaller;
        marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, StringUtil.ENCODING_UTF8);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
        marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);
        return marshaller;
    } catch (JAXBException e) {
        throw new RuntimeException(e);
    }
}
 
Example #9
Source File: JerseyValidationTest.java    From parsec-libraries with Apache License 2.0 5 votes vote down vote up
@Override
protected void configureClient(final ClientConfig config) {
    super.configureClient(config);
    config.register(MoxyJsonFeature.class)
          .property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, true)
          .register(new MoxyJsonConfig().setFormattedOutput(true)
                  // Turn off BV otherwise the entities on server would be validated by MOXy as well.
                  .property(MarshallerProperties.BEAN_VALIDATION_MODE, BeanValidationMode.NONE).resolver());
}
 
Example #10
Source File: JaxbUtils.java    From TranskribusCore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Do not use. The JSON representations produced will differ from the ones the API produces/accepts!
 * 
 * @param object
 * @param doFormatting
 * @param nestedClasses
 * @return
 * @throws JAXBException
 */
private static <T> Marshaller createJsonMarshaller(T object, boolean doFormatting, Class<?>... nestedClasses) throws JAXBException {
	Class<?>[] targetClasses = merge(object.getClass(), nestedClasses);
	JAXBContext jc = org.eclipse.persistence.jaxb.JAXBContextFactory.createContext(targetClasses, Collections.<String,Object>emptyMap());
	Marshaller marshaller = jc.createMarshaller();
	// Set the Marshaller media type to JSON or XML		 
	marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
       marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, doFormatting);
       marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
       // If true then the JSON root element is included in the JSON output. Keep it false to make it compliant to the API
       marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);
       return marshaller;
}
 
Example #11
Source File: JAXBWriter.java    From subsonic with GNU General Public License v3.0 5 votes vote down vote up
private Marshaller createJsonMarshaller() throws JAXBException {
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_ENCODING, StringUtil.ENCODING_UTF8);
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
    marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);
    return marshaller;
}
 
Example #12
Source File: JqmRestApp.java    From jqm with Apache License 2.0 4 votes vote down vote up
public JqmRestApp(@Context ServletContext context)
{
    log.debug("Starting REST WS app");

    // These two properties ensure lists are properly named in JSON objects
    this.property(MarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
    this.property(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);

    // Determine which of the three APIs should be loaded
    boolean loadApiSimple;
    boolean loadApiClient;
    boolean loadApiAdmin;

    try (DbConn cnx = Helpers.getDbSession())
    {
        if (context.getInitParameter("jqmnodeid") != null)
        {
            // The application is running hosted by a JQM node.
            Node n = null;

            try
            {
                n = Node.select_single(cnx, "node_select_by_id", Integer.parseInt(context.getInitParameter("jqmnodeid")));
            }
            catch (NoResultException e)
            {
                throw new RuntimeException("invalid configuration: no node of ID " + context.getInitParameter("jqmnodeid"));
            }
            loadApiSimple = !Boolean.parseBoolean(GlobalParameter.getParameter(cnx, "disableWsApiSimple", "false"));
            loadApiClient = !Boolean.parseBoolean(GlobalParameter.getParameter(cnx, "disableWsApiClient", "false"));
            loadApiAdmin = !Boolean.parseBoolean(GlobalParameter.getParameter(cnx, "disableWsApiAdmin", "false"));

            loadApiAdmin = loadApiAdmin && (n.getLoadApiAdmin() == null ? false : n.getLoadApiAdmin());
            loadApiClient = loadApiClient && (n.getLoadApiClient() == null ? false : n.getLoadApiClient());
            loadApiSimple = loadApiSimple && (n.getLoapApiSimple() == null ? true : n.getLoapApiSimple());
        }
        else
        {
            // The application is hosted by some other server (Tomcat, JBoss... but not a JQM node)

            // Never load the simple API when not running on JQM's own server. This API relies on files that are local to the JQM
            // server.
            loadApiSimple = false;
            // Always load the two others
            loadApiAdmin = true;
            loadApiClient = true;
        }
    }

    // Load the APIs
    if (loadApiAdmin)
    {
        log.debug("\tRegistering admin service");
        this.register(ServiceAdmin.class);
    }
    if (loadApiClient)
    {
        log.debug("\tRegistering client service");
        this.register(ServiceClient.class);
    }
    if (loadApiSimple)
    {
        log.debug("\tRegistering simple service");
        this.register(ServiceSimple.class);
    }

    // Load the exception mappers
    this.register(ErrorHandler.class);
    this.register(JqmExceptionMapper.class);
    this.register(JqmInternalExceptionMapper.class);

    // Logger
    this.register(ExceptionLogger.class);

    // Load the cache annotation helper
    this.register(HttpCacheImpl.class);
}
 
Example #13
Source File: JSONExporter.java    From txtUML with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Serializes an Object to JSON and writes it using the writer provided
 * 
 * @param object
 *            Object to write as JSON, which must have a no-arg constructor.
 * @param jsonfile
 *            BufferedWriter to write JSON Object into
 * @throws JAXBException
 */
public static void writeObjectAsJSON(Object object, BufferedWriter jsonfile) throws JAXBException {
	JAXBContext jc = JAXBContextFactory.createContext(new Class[] { object.getClass(), ObjectFactory.class }, null);
	Marshaller marshaller = jc.createMarshaller();
	marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
	marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);
	marshaller.marshal(object, jsonfile);
}