当前位置: 首页>>代码示例>>Java>>正文


Java XmlRootElement类代码示例

本文整理汇总了Java中javax.xml.bind.annotation.XmlRootElement的典型用法代码示例。如果您正苦于以下问题:Java XmlRootElement类的具体用法?Java XmlRootElement怎么用?Java XmlRootElement使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


XmlRootElement类属于javax.xml.bind.annotation包,在下文中一共展示了XmlRootElement类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: canRead

import javax.xml.bind.annotation.XmlRootElement; //导入依赖的package包/类
/**
 * {@inheritDoc}
 * <p>Jaxb2CollectionHttpMessageConverter can read a generic
 * {@link Collection} where the generic type is a JAXB type annotated with
 * {@link XmlRootElement} or {@link XmlType}.
 */
@Override
public boolean canRead(Type type, Class<?> contextClass, MediaType mediaType) {
	if (!(type instanceof ParameterizedType)) {
		return false;
	}
	ParameterizedType parameterizedType = (ParameterizedType) type;
	if (!(parameterizedType.getRawType() instanceof Class)) {
		return false;
	}
	Class<?> rawType = (Class<?>) parameterizedType.getRawType();
	if (!(Collection.class.isAssignableFrom(rawType))) {
		return false;
	}
	if (parameterizedType.getActualTypeArguments().length != 1) {
		return false;
	}
	Type typeArgument = parameterizedType.getActualTypeArguments()[0];
	if (!(typeArgument instanceof Class)) {
		return false;
	}
	Class<?> typeArgumentClass = (Class<?>) typeArgument;
	return (typeArgumentClass.isAnnotationPresent(XmlRootElement.class) ||
			typeArgumentClass.isAnnotationPresent(XmlType.class)) && canRead(mediaType);
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:31,代码来源:Jaxb2CollectionHttpMessageConverter.java

示例2: getShortName

import javax.xml.bind.annotation.XmlRootElement; //导入依赖的package包/类
/**
 * Returns a short name for this node which can be useful for ID generation or referring to related resources like images
 *
 * @return defaults to "node" but derived nodes should overload this to provide a unique name
 */
@Override
public String getShortName() {
    if (shortName == null) {
        XmlRootElement root = getClass().getAnnotation(XmlRootElement.class);
        if (root != null) {
            shortName = root.name();
        }
        if (shortName == null) {
            XmlType type = getClass().getAnnotation(XmlType.class);
            if (type != null) {
                shortName = type.name();
            }
        }
    }
    return shortName;
}
 
开发者ID:HydAu,项目名称:Camel,代码行数:22,代码来源:OptionalIdentifiedDefinition.java

示例3: parseElementName

import javax.xml.bind.annotation.XmlRootElement; //导入依赖的package包/类
/**
 * Parses an {@link XmlRootElement} annotation on a class
 * and determine the element name.
 *
 * @return null
 *      if none was found.
 */
protected final QName parseElementName(ClassDeclT clazz) {
    XmlRootElement e = reader().getClassAnnotation(XmlRootElement.class,clazz,this);
    if(e==null)
        return null;

    String local = e.name();
    if(local.equals("##default")) {
        // if defaulted...
        local = NameConverter.standard.toVariableName(nav().getClassShortName(clazz));
    }
    String nsUri = e.namespace();
    if(nsUri.equals("##default")) {
        // if defaulted ...
        XmlSchema xs = reader().getPackageAnnotation(XmlSchema.class,clazz,this);
        if(xs!=null)
            nsUri = xs.namespace();
        else {
            nsUri = builder.defaultNsUri;
        }
    }

    return new QName(nsUri.intern(),local.intern());
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:31,代码来源:TypeInfoImpl.java

示例4: serializeRoot

import javax.xml.bind.annotation.XmlRootElement; //导入依赖的package包/类
public void serializeRoot(BeanT bean, XMLSerializer target) throws SAXException, IOException, XMLStreamException {
    if(tagName==null) {
        Class beanClass = bean.getClass();
        String message;
        if (beanClass.isAnnotationPresent(XmlRootElement.class)) {
            message = Messages.UNABLE_TO_MARSHAL_UNBOUND_CLASS.format(beanClass.getName());
        } else {
            message = Messages.UNABLE_TO_MARSHAL_NON_ELEMENT.format(beanClass.getName());
        }
        target.reportError(new ValidationEventImpl(ValidationEvent.ERROR,message,null, null));
    } else {
        target.startElement(tagName,bean);
        target.childAsSoleContent(bean,null);
        target.endElement();
        if (retainPropertyInfo) {
            target.currentProperty.remove();
        }
    }
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:20,代码来源:ClassBeanInfoImpl.java

示例5: createContentType

import javax.xml.bind.annotation.XmlRootElement; //导入依赖的package包/类
/** Returns the contentType for the attachment.
 * The following algorithm is used
 *   - If the input is an array of bytes, then "application/x-download" is returned.
 *   - If the input is a String, then "text/plain" is returned.
 *   - If the input is a File, then a null is returned. The file name should be used to determine the contentType.
 *   - If the input carries the JAXB annotation, then "text/xml" is returned.
 *   - If none of the above are satisfied, then "text/xml" is returned.
 * @param attachment the attachment.
 * @throws FrameworkException If any system error occurs.
 * @throws ApplicationExceptions If any application error occurs.
 * @return the contentType for the attachment.
 */
public static String createContentType(Object attachment)
throws FrameworkException, ApplicationExceptions {
    String contentType = null;
    if (attachment.getClass().isArray() && attachment.getClass().getComponentType() == Byte.TYPE) {
        contentType = CONTENT_TYPE_BYTE_ARRAY;
    } else if (attachment instanceof String) {
        contentType = CONTENT_TYPE_STRING;
    } else if (attachment instanceof File) {
        // Do not set the contentType. It'll be determined based on the file name
    } else if (attachment.getClass().isAnnotationPresent(XmlRootElement.class)) {
        contentType = CONTENT_TYPE_JAXB;
    } else {
        contentType = CONTENT_TYPE_XML_ENCODER;
    }
    return contentType;
}
 
开发者ID:jaffa-projects,项目名称:jaffa-framework,代码行数:29,代码来源:AttachmentService.java

示例6: marshal

import javax.xml.bind.annotation.XmlRootElement; //导入依赖的package包/类
@SuppressWarnings("unchecked")
public static String marshal(Object obj) {
	StringWriter stringWriter = new StringWriter();
	try {
		JAXBContext jaxbContext = JAXBContext.newInstance(obj.getClass());
		Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
		jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
		jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
		XmlRootElement xmlRootAnnotation = obj.getClass().getAnnotation(XmlRootElement.class);
		System.out.println(xmlRootAnnotation);
		if (xmlRootAnnotation == null) {
			XmlType xmlTypeAnnotation = obj.getClass().getAnnotation(XmlType.class);
			QName qname = new QName("", xmlTypeAnnotation.name());
			JAXBElement<Object> jaxbElement = new JAXBElement<Object>(qname, (Class<Object>) obj.getClass(), null, obj);
			jaxbMarshaller.marshal(jaxbElement, stringWriter);
		} else {
			jaxbMarshaller.marshal(obj, stringWriter);
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return stringWriter.toString();
}
 
开发者ID:SoapboxRaceWorld,项目名称:soapbox-race-core,代码行数:24,代码来源:MarshalXML.java

示例7: read

import javax.xml.bind.annotation.XmlRootElement; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Override
public T read(HttpResponseMessage httpResponseMessage, Type expectedType) {
	Class<T> expectedClassType = (Class<T>) expectedType;

	JAXBContext context = contextOf(expectedClassType);

	try {
		Unmarshaller unmarshaller = context.createUnmarshaller();

		StreamSource source = new StreamSource(httpResponseMessage.body());

		XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(source);

		return expectedClassType.isAnnotationPresent(XmlRootElement.class) ? (T) unmarshaller.unmarshal(reader)
				: unmarshaller.unmarshal(reader, expectedClassType).getValue();

	} catch (JAXBException | XMLStreamException | FactoryConfigurationError e) {
		throw new RestifyHttpMessageReadException("Error on try read xml message", e);
	}
}
 
开发者ID:ljtfreitas,项目名称:java-restify,代码行数:22,代码来源:JaxbXmlMessageConverter.java

示例8: process

import javax.xml.bind.annotation.XmlRootElement; //导入依赖的package包/类
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    try {
        if (roundEnv.processingOver()) {
            return true;
        }

        Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(XmlRootElement.class);
        for (Element element : elements) {
            if (element instanceof TypeElement) {
                processModelClass(roundEnv, (TypeElement) element);
            }
        }
    } catch (Throwable e) {
        dumpExceptionToErrorFile("camel-apt-error.log", "Error processing EIP model", e);
    }
    return true;
}
 
开发者ID:HydAu,项目名称:Camel,代码行数:19,代码来源:EipAnnotationProcessor.java

示例9: writeJSonSchemeDocumentation

import javax.xml.bind.annotation.XmlRootElement; //导入依赖的package包/类
protected void writeJSonSchemeDocumentation(PrintWriter writer, RoundEnvironment roundEnv, TypeElement classElement, XmlRootElement rootElement,
                                            String javaTypeName, String modelName) {
    // gather eip information
    EipModel eipModel = findEipModelProperties(roundEnv, classElement, javaTypeName, modelName);

    // get endpoint information which is divided into paths and options (though there should really only be one path)
    Set<EipOption> eipOptions = new TreeSet<EipOption>(new EipOptionComparator(eipModel));
    findClassProperties(writer, roundEnv, eipOptions, classElement, classElement, "", modelName);

    // after we have found all the options then figure out if the model accepts input/output
    eipModel.setInput(hasInput(roundEnv, classElement));
    eipModel.setOutput(hasOutput(eipModel, eipOptions));

    String json = createParameterJsonSchema(eipModel, eipOptions);
    writer.println(json);
}
 
开发者ID:HydAu,项目名称:Camel,代码行数:17,代码来源:EipAnnotationProcessor.java

示例10: findQNameForSoapActionOrType

import javax.xml.bind.annotation.XmlRootElement; //导入依赖的package包/类
/**
 * @return determine element name by using the XmlType.name() of the type to
 *         be marshalled and the XmlSchema.namespace() of the package-info
 */
public QName findQNameForSoapActionOrType(String soapAction, Class<?> type) {
    XmlType xmlType = type.getAnnotation(XmlType.class);
    if (xmlType == null || xmlType.name() == null) {
        throw new RuntimeException("The type " + type.getName() + " needs to have an XmlType annotation with name");
    }
    String nameSpace = xmlType.namespace();
    if ("##default".equals(nameSpace)) {
        XmlSchema xmlSchema = type.getPackage().getAnnotation(XmlSchema.class);
        if (xmlSchema != null) {
            nameSpace = xmlSchema.namespace();
        }
    }
    // prefer name from the XmlType, and fallback to XmlRootElement
    String localName = xmlType.name();
    if (ObjectHelper.isEmpty(localName)) {
        XmlRootElement root = type.getAnnotation(XmlRootElement.class);
        if (root != null) {
            localName = root.name();
        }
    }
    return new QName(nameSpace, localName);
}
 
开发者ID:HydAu,项目名称:Camel,代码行数:27,代码来源:TypeNameStrategy.java

示例11: getTagName

import javax.xml.bind.annotation.XmlRootElement; //导入依赖的package包/类
public static String getTagName(Class<?> handled) {
    if (TAG_NAMES.containsKey(handled)) {
        return TAG_NAMES.get(handled);
    }

    XmlType xmlType = handled.getAnnotation(XmlType.class);
    if (xmlType != null && xmlType.name() != null && xmlType.name().trim().length() > 0) {
        TAG_NAMES.put(handled, xmlType.name());
        return xmlType.name();
    } else {
        XmlRootElement xmlRoot = handled.getAnnotation(XmlRootElement.class);
        if (xmlRoot != null && xmlRoot.name() != null && xmlRoot.name().trim().length() > 0) {
            TAG_NAMES.put(handled, xmlRoot.name());
            return xmlRoot.name();
        }
    }
    throw new IllegalArgumentException("XML name not found for " + handled.getName());
}
 
开发者ID:HydAu,项目名称:Camel,代码行数:19,代码来源:StAXUtil.java

示例12: _processPackages

import javax.xml.bind.annotation.XmlRootElement; //导入依赖的package包/类
private void _processPackages(final Set<String> packages) {
 	if (CollectionUtils.hasData(_packages)) {
 		// [1] - Find all types annotated with @XmlRootElement 
 		Set<Class<?>> allPckgsTypes = Sets.newHashSet(); 
 		
List<URL> urls = new ArrayList<URL>();
//urls.addAll(ClasspathHelper.forPackage("javax.xml.bind.annotation"));
 		for (String p : packages) {
 			//Reflections typeScanner = new Reflections(p);
	urls.addAll(ClasspathHelper.forPackage(p));	// see https://code.google.com/p/reflections/issues/detail?id=53
	log.debug("Scanning package {} for @XmlRootElement annotated types",p);
 		}
Reflections typeScanner = new Reflections(new ConfigurationBuilder()
													.setUrls(urls));    				
Set<Class<?>> pckgTypes = typeScanner.getTypesAnnotatedWith(XmlRootElement.class);
if (CollectionUtils.hasData(pckgTypes)) {
		for (Class<?> type : pckgTypes) log.trace(">Type {}",type);
	allPckgsTypes.addAll(pckgTypes);
} else {
	log.debug("NO types annotated with @XmlRootElement");
}
 		// [2] - Process...
 		_processTypes(allPckgsTypes);
 	}
 }
 
开发者ID:opendata-euskadi,项目名称:r01fb,代码行数:26,代码来源:SimpleMarshallerMappingsFromAnnotationsLoader.java

示例13: testOutputDirectory

import javax.xml.bind.annotation.XmlRootElement; //导入依赖的package包/类
/**
 * Sets the main output directory.
 * If the directory does not exist, it will be created.
 */
public void testOutputDirectory() throws Exception
{
   provide();
   ClassLoader loader = getArtefactClassLoader();
   Class<?> responseWrapper = loader.loadClass("org.jboss.test.ws.jaxws.smoke.tools.jaxws.AddResponse");
   XmlRootElement rootElement = (XmlRootElement) responseWrapper.getAnnotation(XmlRootElement.class);
   assertNotNull("@XmlRootElement missing from response wrapper", rootElement);
   assertEquals("Wrong namespace", rootElement.namespace(), "http://foo.bar.com/calculator");
   responseWrapper = loader.loadClass("org.jboss.test.ws.jaxws.smoke.tools.jaxws.ProcessListResponse");
   XmlList xmlList = (XmlList) responseWrapper.getDeclaredField("_return").getAnnotation(XmlList.class);
   assertNotNull("@XmlList missing from response wrapper's _return field", xmlList);
   responseWrapper = loader.loadClass("org.jboss.test.ws.jaxws.smoke.tools.jaxws.ProcessCustomResponse");
   XmlJavaTypeAdapter xmlJavaTypeAdapter = (XmlJavaTypeAdapter)responseWrapper.getDeclaredField("_return").getAnnotation(XmlJavaTypeAdapter.class);
   assertNotNull("@XmlJavaTypeAdapter missing from response wrapper's _return field", xmlJavaTypeAdapter);
   assertEquals("org.jboss.test.ws.jaxws.smoke.tools.CustomAdapter", xmlJavaTypeAdapter.value().getName());
}
 
开发者ID:jbossws,项目名称:jbossws-cxf,代码行数:21,代码来源:WSProviderPlugin.java

示例14: TellervoEntityAssociatedResource

import javax.xml.bind.annotation.XmlRootElement; //导入依赖的package包/类
/**
 * Constructor for read or delete
 * 
 * @param entity a tellervo WS entity to perform an operation on
 * @param queryType one of read or delete
 */
public TellervoEntityAssociatedResource(WSIEntity entity, TellervoRequestType queryType) {
	super(entity.getClass().getAnnotation(XmlRootElement.class).name(), 
			queryType);

	if(entity == null)
		throw new NullPointerException("Entity may not be null");
	
	switch(queryType) {
	case READ:
	case DELETE:
		this.readDeleteOrMergeEntity = entity;
		break;
				
	default:
		throw new IllegalArgumentException("Invalid request type: must be one of READ or DELETE for this method");
	}		
}
 
开发者ID:ltrr-arizona-edu,项目名称:tellervo,代码行数:24,代码来源:TellervoEntityAssociatedResource.java

示例15: toXmlString

import javax.xml.bind.annotation.XmlRootElement; //导入依赖的package包/类
/**
 * Transform xml object to xml string.
 *
 * @param xmlObj        xml object
 * @throws JAXBException
 *
 * @return
 */
public static String toXmlString(Object xmlObj) throws JAXBException {
    Class<?> clazz = xmlObj.getClass();

    if (clazz.getAnnotation(XmlRootElement.class) == null) {
        throw new IllegalArgumentException("Object must be generate by jaxb.");
    }

    JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    StringWriter w = new StringWriter();
    jaxbMarshaller.marshal(xmlObj, w);
    return w.toString();
}
 
开发者ID:saintdan,项目名称:commons-util,代码行数:24,代码来源:JaxbUtils.java


注:本文中的javax.xml.bind.annotation.XmlRootElement类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。