Java Code Examples for javax.xml.bind.Unmarshaller#setProperty()

The following examples show how to use javax.xml.bind.Unmarshaller#setProperty() . 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
/**
 * Template method that can be overridden by concrete JAXB marshallers
 * for custom initialization behavior. Gets called after creation of JAXB
 * {@code Marshaller}, and after the respective properties have been set.
 * <p>The default implementation sets the
 * {@link #setUnmarshallerProperties defined properties}, the
 * {@link #setValidationEventHandler validation event handler}, the
 * {@link #setSchemas schemas}, {@link #setUnmarshallerListener listener},
 * and {@link #setAdapters adapters}.
 */
protected void initJaxbUnmarshaller(Unmarshaller unmarshaller) throws JAXBException {
	if (this.unmarshallerProperties != null) {
		for (String name : this.unmarshallerProperties.keySet()) {
			unmarshaller.setProperty(name, this.unmarshallerProperties.get(name));
		}
	}
	if (this.unmarshallerListener != null) {
		unmarshaller.setListener(this.unmarshallerListener);
	}
	if (this.validationEventHandler != null) {
		unmarshaller.setEventHandler(this.validationEventHandler);
	}
	if (this.adapters != null) {
		for (XmlAdapter<?, ?> adapter : this.adapters) {
			unmarshaller.setAdapter(adapter);
		}
	}
	if (this.schema != null) {
		unmarshaller.setSchema(this.schema);
	}
}
 
Example 2
Source File: Jaxb2Marshaller.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Template method that can be overridden by concrete JAXB marshallers for custom initialization behavior.
 * Gets called after creation of JAXB {@code Marshaller}, and after the respective properties have been set.
 * <p>The default implementation sets the {@link #setUnmarshallerProperties(Map) defined properties}, the {@link
 * #setValidationEventHandler(ValidationEventHandler) validation event handler}, the {@link #setSchemas(Resource[])
 * schemas}, {@link #setUnmarshallerListener(javax.xml.bind.Unmarshaller.Listener) listener}, and
 * {@link #setAdapters(XmlAdapter[]) adapters}.
 */
protected void initJaxbUnmarshaller(Unmarshaller unmarshaller) throws JAXBException {
	if (this.unmarshallerProperties != null) {
		for (String name : this.unmarshallerProperties.keySet()) {
			unmarshaller.setProperty(name, this.unmarshallerProperties.get(name));
		}
	}
	if (this.unmarshallerListener != null) {
		unmarshaller.setListener(this.unmarshallerListener);
	}
	if (this.validationEventHandler != null) {
		unmarshaller.setEventHandler(this.validationEventHandler);
	}
	if (this.adapters != null) {
		for (XmlAdapter<?, ?> adapter : this.adapters) {
			unmarshaller.setAdapter(adapter);
		}
	}
	if (this.schema != null) {
		unmarshaller.setSchema(this.schema);
	}
}
 
Example 3
Source File: Jaxb2Marshaller.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Template method that can be overridden by concrete JAXB marshallers for custom initialization behavior.
 * Gets called after creation of JAXB {@code Marshaller}, and after the respective properties have been set.
 * <p>The default implementation sets the {@link #setUnmarshallerProperties(Map) defined properties}, the {@link
 * #setValidationEventHandler(ValidationEventHandler) validation event handler}, the {@link #setSchemas(Resource[])
 * schemas}, {@link #setUnmarshallerListener(javax.xml.bind.Unmarshaller.Listener) listener}, and
 * {@link #setAdapters(XmlAdapter[]) adapters}.
 */
protected void initJaxbUnmarshaller(Unmarshaller unmarshaller) throws JAXBException {
	if (this.unmarshallerProperties != null) {
		for (String name : this.unmarshallerProperties.keySet()) {
			unmarshaller.setProperty(name, this.unmarshallerProperties.get(name));
		}
	}
	if (this.unmarshallerListener != null) {
		unmarshaller.setListener(this.unmarshallerListener);
	}
	if (this.validationEventHandler != null) {
		unmarshaller.setEventHandler(this.validationEventHandler);
	}
	if (this.adapters != null) {
		for (XmlAdapter<?, ?> adapter : this.adapters) {
			unmarshaller.setAdapter(adapter);
		}
	}
	if (this.schema != null) {
		unmarshaller.setSchema(this.schema);
	}
}
 
Example 4
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 5
Source File: JaxbUtils.java    From TranskribusCore with GNU General Public License v3.0 6 votes vote down vote up
/**
	 * Experimental method for loading an object from a JSON String.
	 * Seems to work with {@link #marshalToJsonStringWithJaxb(Object, boolean)}
	 * 
	 * @param str
	 * @param targetClass
	 * @param nestedClasses
	 * @return
	 * @throws JAXBException
	 */
	public static <T> T unmarshalJson(String str, Class<T> targetClass, Class<?>... nestedClasses) throws JAXBException {
		//this part only works for the representations produced via the JAXB API
		Class<?>[] targetClasses = merge(targetClass, nestedClasses);
		JAXBContext jc = org.eclipse.persistence.jaxb.JAXBContextFactory.createContext(targetClasses, Collections.<String,Object>emptyMap());
		Unmarshaller u = jc.createUnmarshaller();
		u.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
		u.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false);
		
		StringReader sr = new StringReader(str);
//		@SuppressWarnings("unchecked")
//		T object = (T) u.unmarshal(sr);
//		return object;
		
		StreamSource source = new StreamSource(sr);
		JAXBElement<T> element = u.unmarshal(source, targetClass);

		return element.getValue();
	}
 
Example 6
Source File: JAXBHelper.java    From entando-components with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Unmarshal the entity given its representation
 * @param source streamSource object describing the entity
 * @param expected the expected result class
 * @param hasRoot
 * @param isJson
 * @return
 * @throws Throwable
 */
public static Object unmarshall(StreamSource source, Class<?> expected, boolean hasRoot, boolean isJson) throws Throwable {
  Object obj = null;
  JAXBContext jaxbContext = JAXBContext.newInstance(expected);
  Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

  if (null != source && null != expected) {
    // JSON
    if (isJson) {
      jaxbUnmarshaller.setProperty(JAXBContextProperties.JSON_INCLUDE_ROOT,
              hasRoot);
      jaxbUnmarshaller.setProperty(JAXBContextProperties.MEDIA_TYPE,
              "application/json");
      obj = jaxbUnmarshaller.unmarshal(source, expected).getValue();
    } else {
      // XML
      XMLInputFactory xif = XMLInputFactory.newFactory();
      xif.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false);
      XMLStreamReader xsr = xif.createXMLStreamReader(source);

       obj = jaxbUnmarshaller.unmarshal(xsr);
    }
  }
  return obj;
}
 
Example 7
Source File: AbstractJAXBProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected Unmarshaller createUnmarshaller(Class<?> cls, Type genericType, boolean isCollection)
    throws JAXBException {
    JAXBContext context = isCollection ? getCollectionContext(cls)
                                       : getJAXBContext(cls, genericType);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    if (validateInputIfPossible) {
        Schema theSchema = getSchema(cls);
        if (theSchema != null) {
            unmarshaller.setSchema(theSchema);
        }
    }
    if (eventHandler != null) {
        unmarshaller.setEventHandler(eventHandler);
    }
    if (unmarshallerListener != null) {
        unmarshaller.setListener(unmarshallerListener);
    }
    if (uProperties != null) {
        for (Map.Entry<String, Object> entry : uProperties.entrySet()) {
            unmarshaller.setProperty(entry.getKey(), entry.getValue());
        }
    }
    return unmarshaller;
}
 
Example 8
Source File: TopologyMarshaller.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
public Topology readFrom(Class<Topology>                type,
                         Type                           genericType,
                         Annotation[]                   annotations,
                         MediaType                      mediaType,
                         MultivaluedMap<String, String> httpHeaders,
                         InputStream                    entityStream) throws IOException, WebApplicationException {
  Topology topology = null;

  try {
    if (isReadable(type, genericType, annotations, mediaType)) {
      Map<String, Object> properties = Collections.emptyMap();
      JAXBContext context = JAXBContext.newInstance(new Class[]{Topology.class}, properties);

      Unmarshaller u = context.createUnmarshaller();
      u.setProperty(UnmarshallerProperties.MEDIA_TYPE, mediaType.getType() + "/" + mediaType.getSubtype());

      if (mediaType.isCompatible(MediaType.APPLICATION_XML_TYPE)) {
        // Safeguard against entity injection (KNOX-1308)
        XMLInputFactory xif = XMLInputFactory.newFactory();
        xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
        xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        xif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
        XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource(entityStream));
        topology = (Topology) u.unmarshal(xsr);
      } else {
        topology = (Topology) u.unmarshal(entityStream);
      }
    }
  } catch (XMLStreamException | JAXBException e) {
    throw new IOException(e);
  }

  return topology;
}
 
Example 9
Source File: MarshallerPool.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Acquires a unmarshaller and set the properties to the given value, if non-null.
 */
final Unmarshaller acquireUnmarshaller(final Map<String,?> properties) throws JAXBException {
    final Unmarshaller unmarshaller = acquireUnmarshaller();
    if (properties != null) {
        for (final Map.Entry<String,?> entry : properties.entrySet()) {
            unmarshaller.setProperty(entry.getKey(), entry.getValue());
        }
    }
    return unmarshaller;
}
 
Example 10
Source File: DefaultPrimeMeridianTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests marshalling in the GML 3.1 namespace.
 *
 * @throws JAXBException if an error occurred during unmarshalling.
 */
@Test
@DependsOnMethod("testUnmarshall")
public void testUnarshallGML31() throws JAXBException {
    final MarshallerPool pool = getMarshallerPool();
    final Unmarshaller unmarshaller = pool.acquireUnmarshaller();
    unmarshaller.setProperty(XML.GML_VERSION, LegacyNamespaces.VERSION_3_0);
    final DefaultPrimeMeridian pm = (DefaultPrimeMeridian)
            unmarshal(unmarshaller, getGreenwichXml(LegacyNamespaces.GML));
    pool.recycle(unmarshaller);
    assertIsGreenwich(pm);
}
 
Example 11
Source File: DefaultVerticalDatumTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests (un)marshalling of an older version, GML 3.1.
 *
 * @throws JAXBException if an error occurred during unmarshalling.
 *
 * @see <a href="http://issues.apache.org/jira/browse/SIS-160">SIS-160: Need XSLT between GML 3.1 and 3.2</a>
 */
@Test
public void testGML31() throws JAXBException {
    final Version version = new Version("3.1");
    final MarshallerPool pool = getMarshallerPool();
    final Unmarshaller unmarshaller = pool.acquireUnmarshaller();
    unmarshaller.setProperty(XML.GML_VERSION, version);
    final DefaultVerticalDatum datum =
            (DefaultVerticalDatum) unmarshaller.unmarshal(getClass().getResource(GML31_FILE));
    pool.recycle(unmarshaller);
    /*
     * Following attribute exists in GML 3.1 only.
     */
    assertEquals("vertDatumType", VerticalDatumType.GEOIDAL, datum.getVerticalDatumType());
    /*
     * The name, anchor definition and domain of validity are lost because
     * those property does not have the same XML element name (SIS-160).
     * Below is all we have.
     */
    assertEquals("remarks", "Approximates geoid.", datum.getRemarks().toString());
    assertEquals("scope",   "Hydrography.",        datum.getScope().toString());
    /*
     * Test marshalling. We can not yet compare with the original XML file
     * because of all the information lost. This may be fixed in a future
     * SIS version (SIS-160).
     */
    final Marshaller marshaller = pool.acquireMarshaller();
    marshaller.setProperty(XML.GML_VERSION, version);
    final String xml = marshal(marshaller, datum);
    pool.recycle(marshaller);
    assertXmlEquals(
            "<gml:VerticalDatum xmlns:gml=\"" + LegacyNamespaces.GML + "\">\n" +
            "  <gml:remarks>Approximates geoid.</gml:remarks>\n" +
            "  <gml:scope>Hydrography.</gml:scope>\n" +
            "  <gml:verticalDatumType>geoidal</gml:verticalDatumType>\n" +
            "</gml:VerticalDatum>", xml, "xmlns:*");
}
 
Example 12
Source File: KwsJSONUtils.java    From TranskribusCore with GNU General Public License v3.0 3 votes vote down vote up
public static KwPage getFromFile(File file) throws JAXBException{
		
//		Sets system variable to prevent the need for a new properties file just for this...
		System.setProperty("javax.xml.bind.context.factory", "org.eclipse.persistence.jaxb.JAXBContextFactory");
		
		JAXBContext jc = JAXBContext.newInstance(KwPage.class);
		Unmarshaller ums = jc.createUnmarshaller();
		ums.setProperty(JAXBContextProperties.MEDIA_TYPE, "application/json");
		ums.setProperty(JAXBContextProperties.JSON_INCLUDE_ROOT, true);
		
		
		KwPage page = (KwPage) ums.unmarshal(file);
		
		return page;
	}
 
Example 13
Source File: StaxStreamReader.java    From sis with Apache License 2.0 3 votes vote down vote up
/**
 * Delegates to JAXB the unmarshalling of a part of XML document, starting from the current element (inclusive).
 * This method assumes that the reader is on {@link #START_ELEMENT}. After this method invocation, the reader
 * will be on the event <strong>after</strong> {@link #END_ELEMENT}; this implies that the caller will need to
 * invoke {@link XMLStreamReader#getEventType()} instead of {@link XMLStreamReader#next()}.
 *
 * @param  <T>   compile-time value of the {@code type} argument.
 * @param  type  expected type of the object to unmarshal.
 * @return the unmarshalled object, or {@code null} if none.
 * @throws XMLStreamException if the XML stream is closed.
 * @throws JAXBException if an error occurred during unmarshalling.
 * @throws ClassCastException if the unmarshalling result is not of the expected type.
 *
 * @see javax.xml.bind.Unmarshaller#unmarshal(XMLStreamReader, Class)
 */
protected final <T> T unmarshal(final Class<T> type) throws XMLStreamException, JAXBException {
    Unmarshaller m = unmarshaller;
    if (m == null) {
        m = getMarshallerPool().acquireUnmarshaller();
        for (final Map.Entry<String,?> entry : ((Map<String,?>) owner.configuration).entrySet()) {
            m.setProperty(entry.getKey(), entry.getValue());
        }
    }
    unmarshaller = null;
    final JAXBElement<T> element = m.unmarshal(reader, type);
    unmarshaller = m;                                           // Allow reuse or recycling only on success.
    isNextDone = true;
    return element.getValue();
}