Skip to main content


Eclipse Community Forums
Forum Search:

Search      Help    Register    Login    Home
Home » Eclipse Projects » EclipseLink » Moxy cannot consume json content generated by itself(Jersey2.21 with Moxy for RESTful webservice in XMl and json format )
Moxy cannot consume json content generated by itself [message #1706064] Fri, 21 August 2015 14:21
harry sheng is currently offline harry shengFriend
Messages: 62
Registered: July 2009
Member
Environment: Java 7, Jersey 2.21 and Moxy, with JAXB model for SOAP webservice

The Application:
public class SamoMoxyApplication extends Application {
	
	private final Set<Class<?>> classes = new HashSet<Class<?>>();
	private final Set<Object> singletons = new HashSet<Object>();
	private final Map<String, Object> properties = new HashMap<String, Object>();
	
	
	public SamoMoxyApplication() {
		// resource classes
		classes.add(SamoMoxyResource.class);
		
		// properties
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
//		URL url = classLoader.getResource("META-INF/config/mdm-oxm.xml");
//		properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, url.toString());
		
		properties.put(JAXBContextProperties.JSON_ATTRIBUTE_PREFIX, "@");
		properties.put(JAXBContextProperties.DEFAULT_TARGET_NAMESPACE, "xmlapi_1.0");

		Map<String, String> nsMapping = new HashMap<String, String>();
//		nsMapping.put("xmlapi_1.0", "");
		nsMapping.put(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "xsi");
		properties.put(JAXBContextProperties.NAMESPACE_PREFIX_MAPPER, nsMapping);
		
		// singletons
		Class[] jaxbClasses = SamoTypeResolver.getSamoJaxbTypes().toArray(new Class[0]);
		
		MoxyXmlFeature xmlFeature = new MoxyXmlFeature(properties, classLoader, false, jaxbClasses);
		singletons.add(xmlFeature);

		MdmMoxyJaxbContextResolver moxyContextResolver = new MdmMoxyJaxbContextResolver(properties, jaxbClasses);
		singletons.add(moxyContextResolver);
		
		MdmMoxyJsonConfigResolver jsonConfigResolver = new MdmMoxyJsonConfigResolver();
		singletons.add(jsonConfigResolver);
	}
	
	@Override
    public Set<Class<?>> getClasses() {
        return classes;
    }

	@Override
    public Set<Object> getSingletons() {
        return singletons;
    }
    
	@Override
    public Map<String, Object> getProperties() {
		return properties;
    }
}


The JaxbContextResolver:
@Provider
@Produces( {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML} )
public class MdmMoxyJaxbContextResolver implements ContextResolver<JAXBContext> {

	private static Logger logger = LoggerFactory.getLogger(MdmMoxyJaxbContextResolver.class);
	
	private final Map<String, Object> properties;
	private final Class[] classes;
	private JAXBContext jaxbContext;

	
	public MdmMoxyJaxbContextResolver(
			Map<String, Object> properties,
            Class... classes)
	{
        this.properties = properties == null ? Collections.<String, Object>emptyMap() : properties;
        this.classes = classes;
    }
	
	@Override
	public JAXBContext getContext(Class<?> type) {
		if (Arrays.asList(classes).contains(type)) {
			if (jaxbContext == null) {
				try {
					long t1 = System.currentTimeMillis();
					jaxbContext = JAXBContextFactory.createContext(classes, properties);
					long t2 = System.currentTimeMillis();
					logger.info("Time to create jaxb context: " + (t2 - t1) + "ms");
				} catch (JAXBException ex) {
					logger.error("getContext()", ex);
				}
			}
			return jaxbContext;
		} else {
			logger.error("Unregistered class : " + type);
			return null;
		}
	}

}


The JsonConfigResolver:
@Provider
public class MdmMoxyJsonConfigResolver implements ContextResolver<MoxyJsonConfig> {

	private final MoxyJsonConfig config;
	
	public MdmMoxyJsonConfigResolver() {
		final Map<String, String> namespacePrefixMapper = new HashMap<String, String>();
		namespacePrefixMapper.put(javax.xml.XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "xsi");
//        namespacePrefixMapper.put("xmlapi_1.0", "");
 
        config = new MoxyJsonConfig()
                .setNamespacePrefixMapper(namespacePrefixMapper)
                .setNamespaceSeparator(':')
                .setAttributePrefix("@")
                .setValueWrapper("value")
                .property(JAXBContextProperties.JSON_WRAPPER_AS_ARRAY_NAME, true)
                .setFormattedOutput(true)
                .setIncludeRoot(true)
                .setMarshalEmptyCollections(true);
	}
	
	@Override
	public MoxyJsonConfig getContext(Class<?> type) {
		return config;
	}

}


The ResourceHandler:
	@GET
	@Path("json/{samoXmlType}")
	@Produces(MediaType.APPLICATION_JSON)
	public Response jsonGetService(
			@PathParam("samoXmlType") String samoXmlType,
			@Context HttpServletRequest request,
			@Context HttpServletResponse response)
			throws Exception
	{
		Class<? extends SamObject> samoJavaType = validateSamoXmlTypeForGetService(samoXmlType);
		Map<String, Object> args = analysisRequestParameters(samoJavaType, request);
		List<? extends SamObject> samoList = samoSearchHandler.find(samoJavaType, args);

		ParameterizedTypeImpl genericType = new ParameterizedTypeImpl(List.class, samoJavaType);
		GenericEntity entity = new GenericEntity(samoList, genericType);

		return Response.ok(entity).build();
	}

	@POST
	@Path("json/{samoXmlType}")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response jsonPostService(
			@PathParam("samoXmlType") String samoXmlType,
			List<ApipeApipe> apipe)
			throws Exception
	{
		Class<? extends SamObject> samoJavaType = validateSamoXmlTypeForGetService(samoXmlType);
		return Response.ok(apipe).build();
	}


The GET request handler generates the following json content:
$ curl -X GET http://localhost:8080/mdm-samo-ws-sp-project-web/rest/samo/json/lag.Interface?objectFullName=network:35.121.34.101:lag:interface-31
[ {
   "@xsi:type" : "ns0:lag.Interface",
   "ns0:objectFullName" : "network:35.121.34.101:lag:interface-31",
   "ns0:selfAlarmed" : true,
   "ns0:name" : "interface-31",
   "ns0:administrativeState" : "portInService",
   "ns0:baseMacAddress" : "00-00-00-00-00-00",
   "ns0:cleiCode" : "N/A",
   "ns0:displayedName" : "Lag 31",
   "ns0:equipmentCategory" : "port",
   "ns0:equipmentState" : "equipmentOperationallyDown",
   "ns0:hardwareFailureReason" : "N/A",
   "ns0:hwIndex" : 0,
   "ns0:hwName" : "N/A",
   "ns0:isEquipped" : true,
   "ns0:manufactureDate" : "N/A",
   "ns0:manufacturer" : "N/A",
   "ns0:manufacturerBoardNumber" : "N/A",
   "ns0:olcState" : "inService",
   "ns0:operationalState" : "portOutOfService",
   "ns0:serialNumber" : "N/A",
   "ns0:shelfId" : 1,
   "ns0:siteId" : "35.121.34.101",
   "ns0:siteName" : "Demo_1",
   "ns0:portId" : 0,
   "ns0:accountingPolicyObjectPointer" : "",
   "ns0:collectStats" : false,
   "ns0:description" : "A Test LAG",
   "ns0:encapType" : "qEncap",
   "ns0:holdTimeDown" : 0,
   "ns0:holdTimeUp" : 0,
   "ns0:isl2UplinkMode" : false,
   "ns0:macAddress" : "44-65-FF-00-01-5F",
   "ns0:mode" : "access",
   "ns0:mtuValue" : 0,
   "ns0:networkQueueObjectPointer" : "network:35.121.34.101:Network Queue:default",
   "ns0:portSchedulerPolicyObjectPointer" : "",
   "ns0:speed" : "lineRate",
   "ns0:accountingPolicyCapable" : false,
   "ns0:accountingPolicyId" : 0,
   "ns0:accountingPolicyName" : "",
   "ns0:actualSpeed" : 0,
   "ns0:currentNumberOfChannels" : 0,
   "ns0:hasConnections" : true,
   "ns0:isLinkUp" : false,
   "ns0:isPortChannelALeaf" : false,
   "ns0:networkQueuePolicyCapable" : true,
   "ns0:networkQueuePolicyName" : "default",
   "ns0:numberOfPossibleChannels" : 0,
   "ns0:operationalMTU" : 0,
   "ns0:parentSnmpPortId" : 0,
   "ns0:portCategory" : "lag",
   "ns0:portClass" : "faste",
   "ns0:portName" : "lag-31",
   "ns0:snmpPortId" : 1342177311,
   "ns0:specificCardType" : [ "mda_unknown" ],
   "ns0:specificType" : "port_faste_tx",
   "ns0:state" : "ghost",
   "ns0:portUsage" : "empty",
   "ns0:lagId" : 31,
   "ns0:lagSize" : "2",
   "ns0:lagType" : "lacpOff",
   "ns0:lagName" : "N/A",
   "ns0:portThreshold" : 0,
   "ns0:isMcLagParticipant" : false,
   "ns0:lagSelectedPorts" : 0,
   "ns0:primaryLagMemberId" : 0,
   "ns0:primaryLagMemberName" : "N/A"
} ]


Post the above json content to the POST handler, I get the following:
Exception Description: The class [class javax.ws.rs.core.GenericEntity] cannot be used as the container for the results of a query because it cannot be instantiated.
Internal Exception: java.lang.InstantiationException: javax.ws.rs.core.GenericEntity
        org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:485)
        org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:386)
        org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:334)
        org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
        org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:96)
        org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
        org.springframework.security.util.FilterChainProxy.doFilter(FilterChainProxy.java:169)
        org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:236)
        org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
        org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:112)
        org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)


If I post a single item, instead of a list, back to the POST handler, there's no exception, but the object unmarshalled is NULL.
What is missed in my code?
Previous Topic:Karaf 4.0 and EclipseLink missing dependency
Next Topic:Need to extend existing ComplexType defined in XSD to accept empty strings from XML
Goto Forum:
  


Current Time: Fri Mar 05 08:23:06 GMT 2021

Powered by FUDForum. Page generated in 0.01627 seconds
.:: Contact :: Home ::.

Powered by: FUDforum 3.0.2.
Copyright ©2001-2010 FUDforum Bulletin Board Software

Back to the top