Java Code Examples for javax.xml.bind.JAXBElement

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project litle-sdk-for-java, under directory /lib/jaxb/samples/xml-stylesheet/src/.

Source file: Main.java

  25 
vote

public static void main(String[] args) throws Exception {
  JAXBContext context=JAXBContext.newInstance("primer");
  JAXBElement poe=(JAXBElement)context.createUnmarshaller().unmarshal(new File(args[0]));
  PurchaseOrderType po=(PurchaseOrderType)poe.getValue();
  System.out.println("<?xml version='1.0'?>");
  System.out.println("<?xml-stylesheet type='text/xsl' href='foobar.xsl' ?>");
  Marshaller m=context.createMarshaller();
  m.setProperty(Marshaller.JAXB_FRAGMENT,Boolean.TRUE);
  m.marshal(poe,System.out);
}
 

Example 2

From project repose, under directory /project-set/components/versioning/src/main/java/com/rackspace/papi/components/versioning/.

Source file: VersioningHandler.java

  23 
vote

private void handleVersionedRequest(VersionedRequest versionedRequest,FilterDirector filterDirector,VersionedOriginService targetOriginService) throws VersionedHostNotFoundException, MalformedURLException {
  if (versionedRequest.isRequestForRoot() || versionedRequest.requestMatchesVersionMapping()) {
    final JAXBElement versionElement=VERSIONING_OBJECT_FACTORY.createVersion(new VersionChoiceFactory(targetOriginService.getMapping()).create());
    transformer.transform(versionElement,versionedRequest.getRequestInfo().getPreferedMediaRange(),filterDirector.getResponseOutputStream());
    filterDirector.setResponseStatus(HttpStatusCode.OK);
    filterDirector.setFilterAction(FilterAction.RETURN);
  }
 else {
    RouteDestination dest=filterDirector.addDestination(targetOriginService.getOriginServiceHost(),versionedRequest.asInternalURI(),(float)VERSIONING_DEFAULT_QUALITY);
    dest.setContextRemoved(versionedRequest.getMapping().getId());
    filterDirector.setFilterAction(FilterAction.PASS);
  }
}
 

Example 3

From project core_1, under directory /transform/src/main/java/org/switchyard/transform/jaxb/internal/.

Source file: JAXBMarshalTransformer.java

  22 
vote

@Override public Message transform(Message message){
  Marshaller marshaller;
  try {
    marshaller=_jaxbContext.createMarshaller();
  }
 catch (  JAXBException e) {
    throw new SwitchYardException("Failed to create Marshaller for type '" + getFrom() + "'.",e);
  }
  try {
    StringWriter resultWriter=new StringWriter();
    Object javaObject=message.getContent();
    JAXBElement jaxbElement=new JAXBElement(getTo(),QNameUtil.toJavaMessageType(getFrom()),javaObject);
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE);
    marshaller.marshal(jaxbElement,resultWriter);
    message.setContent(resultWriter.toString());
  }
 catch (  JAXBException e) {
    throw new SwitchYardException("Failed to unmarshall for type '" + getFrom() + "'.",e);
  }
  return message;
}
 

Example 4

From project crest, under directory /entitywriter/src/main/java/org/codegist/crest/serializer/jaxb/.

Source file: JaxbParam.java

  22 
vote

public void setParams(List<Param> params){
  this.params=new ArrayList<JAXBElement<?>>();
  this.classes=new HashSet<Class<?>>();
  this.classes.add(getClass());
  for (  Param entry : params) {
    Class<?> cls=entry.getParamConfig().getValueClass();
    for (    Object value : entry.getValue()) {
      if (value == null)       continue;
      Object valueEl;
      if (isPrimitive(value)) {
        valueEl=value;
      }
 else {
        XmlRootElement root=cls.getAnnotation(XmlRootElement.class);
        String name;
        String ns;
        if (root != null) {
          name="##default".equals(root.name()) ? decapitalize(cls.getSimpleName()) : root.name();
          ns="##default".equals(root.namespace()) ? null : root.namespace();
        }
 else {
          name=decapitalize(cls.getSimpleName());
          ns=null;
        }
        valueEl=new JAXBElement(new QName(ns,name),cls,value);
      }
      JAXBElement entryEl=new JAXBElement(new QName(entry.getParamConfig().getName()),valueEl.getClass(),valueEl);
      this.params.add(entryEl);
    }
    this.classes.addAll(Types.getActors(entry.getParamConfig().getValueGenericType()));
  }
}
 

Example 5

From project ds-annotation-builder, under directory /com.wuetherich.osgi.ds.annotations/src/com/wuetherich/osgi/ds/annotations/internal/.

Source file: AbstractComponentDescription.java

  22 
vote

/** 
 * <p> </p>
 * @throws JAXBException
 */
public boolean equals(InputStream inputStream) throws JAXBException {
  JAXBContext jaxbContext=createJAXBContext();
  Unmarshaller unmarshaller=jaxbContext.createUnmarshaller();
  JAXBElement<Tcomponent> jaxbElement=(JAXBElement<Tcomponent>)unmarshaller.unmarshal(inputStream);
  Tcomponent tcomponent=jaxbElement.getValue();
  if (!tcomponent.equals(_tcomponent)) {
    System.out.println(tcomponent);
    System.out.println(_tcomponent);
  }
  return tcomponent.equals(_tcomponent);
}
 

Example 6

From project PID-webservice, under directory /server/src/main/java/org/socialhistoryservices/pid/database/dao/.

Source file: HandleDaoImpl.java

  21 
vote

/** 
 * add locations without namespace as Handle System describes it. The namespace will have to be removed to make sure future implementations of the Handle System process the XML correctly: <locations><location></location></locations>
 * @param handle    The persistent identifier
 * @param locations The 10320/loc value
 */
private void setLocations(Handle handle,LocAttType locations){
  final JAXBElement element=new JAXBElement(qname,PidType.class,LocAttType.class,locations);
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  StreamResult result=new StreamResult(baos);
  marshaller.marshal(element,result);
  ByteArrayOutputStream os=new ByteArrayOutputStream();
  Result result2=new StreamResult(os);
  final StreamSource xmlSource=new StreamSource(new ByteArrayInputStream(baos.toByteArray()));
  try {
    transformer.transform(xmlSource,result2);
  }
 catch (  TransformerException e) {
    e.printStackTrace();
  }
  handle.setData(os.toByteArray());
}
 

Example 7

From project s-ramp, under directory /s-ramp-api/src/test/java/org/s_ramp/xmlns/_2010/s_ramp/.

Source file: XsdDocumentTest.java

  21 
vote

/** 
 * Unmarshall an xml fragment.
 */
@Test public void unmarshall(){
  try {
    JAXBContext jaxbContext=JAXBContext.newInstance("org.s_ramp.xmlns._2010.s_ramp");
    Unmarshaller unMarshaller=jaxbContext.createUnmarshaller();
    Assert.assertNotNull("Cannot locate file XsdDocument-entry.xml",this.getClass().getResourceAsStream("XsdDocument-entry.xml"));
    String expectedXML=new Scanner(this.getClass().getResourceAsStream("XsdDocument-entry.xml")).useDelimiter("\\Z").next();
    StringReader reader=new StringReader(expectedXML);
    JAXBElement<Artifact> element=unMarshaller.unmarshal(new StreamSource(reader),Artifact.class);
    Artifact artifact=element.getValue();
    Assert.assertEquals("accountingTypes.xsd",artifact.getXsdDocument().getName());
  }
 catch (  JAXBException jaxbe) {
    jaxbe.printStackTrace();
    fail("No exception should be thrown");
  }
}
 

Example 8

From project droolsjbpm-integration, under directory /drools-pipeline/src/main/java/org/drools/runtime/pipeline/impl/.

Source file: JaxbFromXmlTransformer.java

  20 
vote

public void receive(Object object,PipelineContext context){
  Object result=null;
  try {
    if (object instanceof File) {
      result=this.unmarshaller.unmarshal((File)object);
    }
 else     if (object instanceof InputStream) {
      result=this.unmarshaller.unmarshal((InputStream)object);
    }
 else     if (object instanceof Reader) {
      result=this.unmarshaller.unmarshal((Reader)object);
    }
 else     if (object instanceof Source) {
      result=this.unmarshaller.unmarshal((Source)object);
    }
 else     if (object instanceof InputSource) {
      result=this.unmarshaller.unmarshal((InputSource)object);
    }
 else     if (object instanceof Resource) {
      result=this.unmarshaller.unmarshal(((Resource)object).getReader());
    }
 else     if (object instanceof String) {
      result=this.unmarshaller.unmarshal(new StringReader((String)object));
    }
 else {
      throw new IllegalArgumentException("signal object must be instance of File, InputStream, Reader, Source, InputSource, Resource, String");
    }
  }
 catch (  Exception e) {
    handleException(this,object,e);
  }
  if (result instanceof JAXBElement) {
    result=((JAXBElement)object).getValue();
  }
  emit(result,context);
}
 

Example 9

From project fedora-client, under directory /fedora-client-core/src/main/java/com/yourmediashelf/fedora/client/response/.

Source file: DatastreamProfileResponse.java

  20 
vote

/** 
 * Get the datastreamProfile. Note this method will fail if the request specified format=html rather than xml.
 * @return the DatastreamProfile
 * @throws FedoraClientException
 */
public DatastreamProfile getDatastreamProfile() throws FedoraClientException {
  if (datastreamProfile == null) {
    @SuppressWarnings("unchecked") JAXBElement<DatastreamProfile> root=(JAXBElement<DatastreamProfile>)unmarshallResponse(ContextPath.Management);
    datastreamProfile=root.getValue();
  }
  return datastreamProfile;
}
 

Example 10

From project gedcomx, under directory /gedcomx-rt-support/src/main/java/org/gedcomx/rt/json/.

Source file: ExtensibleObjectDeserializer.java

  20 
vote

@Override protected void handleUnknownProperty(JsonParser jp,DeserializationContext ctxt,Object beanOrClass,String propName) throws IOException, JsonProcessingException {
  if (beanOrClass instanceof SupportsExtensionElements) {
    SupportsExtensionElements target=(SupportsExtensionElements)beanOrClass;
    Class<?> type=GedcomNamespaceManager.getKnownJsonType(propName);
    if (type != null) {
      if (HasJsonKey.class.isAssignableFrom(type)) {
        for (        Object ext : readKeyedMapOf(type,jp,ctxt)) {
          target.addExtensionElement(ext);
        }
      }
 else {
        for (        Object ext : readArrayOf(type,jp,ctxt)) {
          target.addExtensionElement(ext);
        }
      }
      return;
    }
 else {
      QName wrapper=getWrapperName(propName);
      type=GedcomNamespaceManager.getWrappedTypeForJsonName(propName);
      if (type != null) {
        List<?> objects=readArrayOf(type,jp,ctxt);
        for (        Object ext : objects) {
          target.addExtensionElement(new JAXBElement(wrapper,type,ext));
        }
        return;
      }
    }
  }
  if (beanOrClass instanceof SupportsExtensionAttributes && jp.getCurrentToken().isScalarValue()) {
    ((SupportsExtensionAttributes)beanOrClass).addExtensionAttribute(getWrapperName(propName),jp.getText());
    return;
  }
  super.handleUnknownProperty(jp,ctxt,beanOrClass,propName);
}
 

Example 11

From project GoFleetLSServer, under directory /src/main/java/org/gofleet/openLS/util/.

Source file: Utils.java

  20 
vote

/** 
 * Envelops an  {@link AbstractResponseParametersType} response inside the{@link XLSType}
 * @param element
 * @return
 * @throws AxisFault
 */
@SuppressWarnings({"rawtypes","unchecked"}) public static JAXBElement<XLSType> envelop(List<List<AbstractResponseParametersType>> params,Locale locale){
  XLSType xlsType=new XLSType();
  xlsType.setVersion(BigDecimal.valueOf(1.2d));
  ResponseType responseType=new ResponseType();
  for (  List<AbstractResponseParametersType> element : params) {
    if (element != null)     for (    AbstractResponseParametersType e : element) {
      String responseClass=e.getClass().getSimpleName().toString();
      responseClass=responseClass.substring(0,responseClass.length() - 4);
      JAXBElement<? extends AbstractResponseParametersType> body_=new JAXBElement(new QName("http://www.opengis.net/xls",responseClass,"xls"),e.getClass(),e);
      responseType.setResponseParameters(body_);
    }
    responseType.setNumberOfResponses(new BigInteger((new Integer(element.size())).toString()));
    responseType.setRequestID("-1");
    responseType.setVersion("0.9");
    xlsType.getBody().add(new JAXBElement(new QName("http://www.opengis.net/xls","Response","xls"),responseType.getClass(),responseType));
  }
  ResponseHeaderType header=new ResponseHeaderType();
  header.setSessionID("none");
  xlsType.setHeader(new JAXBElement<ResponseHeaderType>(new QName("http://www.opengis.net/xls","ResponseHeader","xls"),ResponseHeaderType.class,header));
  xlsType.setLang(locale.getLanguage());
  JAXBElement<XLSType> res=new JAXBElement<XLSType>(new QName("http://www.opengis.net/xls","xls","xls"),XLSType.class,xlsType);
  return res;
}
 

Example 12

From project harmony, under directory /harmony.common.serviceinterface/src/main/java/org/opennaas/extensions/idb/serviceinterface/databinding/utils/.

Source file: JaxbSerializer.java

  20 
vote

/** 
 * Convert Object to XML.
 * @param obj Object to be converted to a XML-String
 * @return XML String XML-String derived out of Object
 * @throws JAXBException A JAXBException
 */
@Override @SuppressWarnings("unchecked") public String objectToXml(final Object obj) throws JAXBException {
  final ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
  final StreamResult result=new StreamResult(outputStream);
  try {
    if (obj.getClass().isAnnotationPresent(XmlRootElement.class)) {
      this.marshaller.marshal(obj,result);
    }
 else {
      final Class<?> objClass=obj.getClass();
      this.marshaller.marshal(new JAXBElement(new QName(objClass.getName()),objClass,obj),result);
    }
  }
 catch (  final NullPointerException npe) {
    throw new JAXBException(npe.getMessage() + "\n\nMay be caused by an invalid XMLGregorianCalendar.\n" + "Please make shure to use the generateXMLCalendar"+ " method from Helpers to create new Calendars to"+ " avoid illegal calendar states",npe);
  }
  return (outputStream.toString());
}
 

Example 13

From project ODE-X, under directory /runtime/src/main/java/org/apache/ode/runtime/exec/platform/.

Source file: MessageHandler.java

  20 
vote

public void log(LogLevel level,int code,String messageText,String targetNodeId,String targetClusterId,String taskId){
  try {
    org.apache.ode.spi.exec.platform.xml.Message xmlMessage=new org.apache.ode.spi.exec.platform.xml.Message();
    xmlMessage.setLevel(org.apache.ode.spi.exec.platform.xml.LogLevel.valueOf(level.toString()));
    xmlMessage.setCode(BigInteger.valueOf(code));
    xmlMessage.setValue(messageText);
    xmlMessage.setTimestamp(Calendar.getInstance());
    BytesMessage message=pollMsgSession.createBytesMessage();
    message.setStringProperty(Node.NODE_MQ_PROP_NODE,targetNodeId);
    message.setStringProperty(Node.NODE_MQ_PROP_CLUSTER,targetClusterId);
    message.setStringProperty(MSG_MQ_ORIG_NODE,nodeId);
    message.setStringProperty(MSG_MQ_ORIG_CLUSTER,clusterId);
    message.setStringProperty(MSG_MQ_TASK,taskId);
    Marshaller marshaller=NodeImpl.PLATFORM_JAXB_CTX.createMarshaller();
    ByteArrayOutputStream bos=new ByteArrayOutputStream();
    marshaller.marshal(new JAXBElement(new QName(CLUSTER_NAMESPACE,"Message"),org.apache.ode.spi.exec.platform.xml.Message.class,xmlMessage),bos);
    message.writeBytes(bos.toByteArray());
    producer.send(message);
  }
 catch (  Exception je) {
    log.log(Level.SEVERE,"",je);
  }
}
 

Example 14

From project bundlemaker, under directory /main/org.bundlemaker.core/src/org/bundlemaker/core/internal/projectdescription/.

Source file: XmlProjectDescriptionExporterUtils.java

  19 
vote

/** 
 * <p> </p>
 * @param outputStream
 * @return
 */
public static XmlProjectDescriptionType unmarshal(InputStream inputStream){
  try {
    JaxbCompoundClassLoader jaxbCompoundClassLoader=new JaxbCompoundClassLoader();
    JAXBContext jaxbContext=JAXBContext.newInstance(jaxbCompoundClassLoader.getPackageString(),jaxbCompoundClassLoader.getCompoundClassLoader());
    Unmarshaller unmarshaller=jaxbContext.createUnmarshaller();
    JAXBElement<XmlProjectDescriptionType> root=unmarshaller.unmarshal(new StreamSource(inputStream),XmlProjectDescriptionType.class);
    return root.getValue();
  }
 catch (  Exception e) {
    throw new RuntimeException(e.getMessage(),e);
  }
}
 

Example 15

From project commons-j, under directory /src/main/java/nerds/antelax/commons/xml/saxbp/.

Source file: ParseInterest.java

  19 
vote

private static Class<?> checkAndGetJaxbClass(final Method method) throws SAXBPException {
  final Class<?>[] methodArgTypes=method.getParameterTypes();
  if (methodArgTypes.length != 1 || !JAXBElement.class.getName().equals(methodArgTypes[0].getName()))   throw new SAXBPException("JAXB handler method must take a single argument of type JAXBElement<...>");
  final Type jaxbType=((ParameterizedType)method.getGenericParameterTypes()[0]).getActualTypeArguments()[0];
  if (!(jaxbType instanceof Class<?>))   throw new SAXBPException("JAXB handler method must take a single argument of type JAXBElement<...>");
  return (Class<?>)jaxbType;
}
 

Example 16

From project geolatte-maprenderer, under directory /src/main/java/org/geolatte/maprenderer/sld/.

Source file: FeatureTypeStyle.java

  19 
vote

private List<AbstractSymbolizer> createSymbolizers(RuleType ruleType){
  List<AbstractSymbolizer> symbolizers=new ArrayList<AbstractSymbolizer>();
  for (  JAXBElement<? extends SymbolizerType> symbolizerElement : ruleType.getSymbolizer()) {
    createAndAddSymbolizer(symbolizerElement.getValue(),symbolizerElement.getDeclaredType(),symbolizers);
  }
  return symbolizers;
}
 

Example 17

From project GNDMS, under directory /model/src/de/zib/gndms/c3resource/.

Source file: C3ResourceReader.java

  19 
vote

public C3GridResource next(){
  try {
    if (hasNext()) {
      final JAXBElement<C3GridResource> element=unmarshaller.unmarshal(resourceReader,C3GridResource.class);
      return element.getValue();
    }
 else     throw new NoSuchElementException();
  }
 catch (  JAXBException e) {
    throw new IllegalStateException(e);
  }
}
 

Example 18

From project hbc-maven-core, under directory /src/main/java/org/hardisonbrewing/jaxb/.

Source file: JAXB.java

  19 
vote

public static <T>T unmarshal(InputStream inputStream,Class<T> clazz) throws JAXBException {
  Object object;
  try {
    Unmarshaller unmarshaller=getUnmarshaller(clazz);
    object=unmarshaller.unmarshal(inputStream);
  }
 catch (  JAXBException e) {
    JoJoMojo.getMojo().getLog().error("",e);
    throw e;
  }
  if (object instanceof JAXBElement) {
    JAXBElement<T> jaxbElement=(JAXBElement<T>)object;
    return jaxbElement.getValue();
  }
  return (T)object;
}
 

Example 19

From project hibernate-validator, under directory /engine/src/main/java/org/hibernate/validator/internal/xml/.

Source file: ValidationXmlParser.java

  19 
vote

private ValidationConfigType unmarshal(InputStream inputStream,Schema schema){
  log.parsingXMLFile(VALIDATION_XML_FILE);
  try {
    JAXBContext jc=JAXBContext.newInstance(ValidationConfigType.class);
    Unmarshaller unmarshaller=jc.createUnmarshaller();
    unmarshaller.setSchema(schema);
    StreamSource stream=new StreamSource(inputStream);
    JAXBElement<ValidationConfigType> root=unmarshaller.unmarshal(stream,ValidationConfigType.class);
    return root.getValue();
  }
 catch (  JAXBException e) {
    throw log.getUnableToParseValidationXmlFileException(VALIDATION_XML_FILE,e);
  }
}
 

Example 20

From project Ivory, under directory /oozie/src/main/java/org/apache/ivory/converter/.

Source file: AbstractOozieEntityMapper.java

  19 
vote

protected void marshal(Cluster cluster,JAXBElement<?> jaxbElement,JAXBContext jaxbContext,Path outPath) throws IvoryException {
  try {
    Marshaller marshaller=jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE);
    FileSystem fs=outPath.getFileSystem(ClusterHelper.getConfiguration(cluster));
    OutputStream out=fs.create(outPath);
    try {
      marshaller.marshal(jaxbElement,out);
    }
  finally {
      out.close();
    }
    if (LOG.isDebugEnabled()) {
      StringWriter writer=new StringWriter();
      marshaller.marshal(jaxbElement,writer);
      LOG.debug("Writing definition to " + outPath + " on cluster "+ cluster.getName());
      LOG.debug(writer.getBuffer());
    }
    LOG.info("Marshalled " + jaxbElement.getDeclaredType() + " to "+ outPath);
  }
 catch (  Exception e) {
    throw new IvoryException("Unable to marshall app object",e);
  }
}
 

Example 21

From project JAXB-classes-for-SVG, under directory /src/main/java/org/plutext/jaxb/svg11/.

Source file: SVGAnimateColorContent.java

  19 
vote

/** 
 * Gets the value of the svgDescriptionClass property. <p> This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE> method for the svgDescriptionClass property. <p> For example, to add a new item, do as follows: <pre> getSVGDescriptionClass().add(newItem); </pre> <p> Objects of the following type(s) are allowed in the list {@link JAXBElement }{@code <}{@link Desc }{@code >}{@link JAXBElement }{@code <}{@link Metadata }{@code >}{@link JAXBElement }{@code <}{@link Object }{@code >}{@link JAXBElement }{@code <}{@link Title }{@code >}
 */
public List<JAXBElement<?>> getSVGDescriptionClass(){
  if (svgDescriptionClass == null) {
    svgDescriptionClass=new ArrayList<JAXBElement<?>>();
  }
  return this.svgDescriptionClass;
}
 

Example 22

From project jbosgi, under directory /testsuite/example/src/test/java/org/jboss/test/osgi/example/jaxb/.

Source file: XMLBindingTestCase.java

  19 
vote

@Test @SuppressWarnings("unchecked") public void testUnmarshaller() throws Exception {
  JAXBContext jaxbContext=JAXBContext.newInstance(ObjectFactory.class.getPackage().getName(),ObjectFactory.class.getClassLoader());
  Unmarshaller unmarshaller=jaxbContext.createUnmarshaller();
  URL resURL=bundle.getResource("booking.xml");
  JAXBElement<CourseBooking> rootElement=(JAXBElement<CourseBooking>)unmarshaller.unmarshal(resURL.openStream());
  assertNotNull("root element not null",rootElement);
  CourseBooking booking=rootElement.getValue();
  assertNotNull("booking not null",booking);
  CompanyType company=booking.getCompany();
  assertNotNull("company not null",company);
  assertEquals("ACME Consulting",company.getName());
}
 

Example 23

From project JRebirth, under directory /org.jrebirth/presentation/src/main/java/org/jrebirth/presentation/service/.

Source file: PresentationService.java

  19 
vote

/** 
 * {@inheritDoc}
 */
@Override public void ready() throws CoreException {
  super.ready();
  try {
    final JAXBContext jaxbContext=JAXBContext.newInstance("org.jrebirth.presentation.model");
    final Unmarshaller unmarshaller=jaxbContext.createUnmarshaller();
    final InputStreamReader in=new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(CONFIG_NAME + ".xml"),Charset.forName("UTF-8"));
    final XMLStreamReader xsr=XMLInputFactory.newInstance().createXMLStreamReader(in);
    this.presentation=Presentation.class.cast(JAXBElement.class.cast(unmarshaller.unmarshal(xsr)).getValue());
  }
 catch (  final JAXBException|XMLStreamException|FactoryConfigurationError e) {
    System.err.println("Impossible to open " + CONFIG_NAME + ".xml");
    e.printStackTrace();
    throw new CoreException("Xml file incorrectly parsed !",e);
  }
}
 

Example 24

From project MEditor, under directory /editor-common/editor-common-server/src/main/java/cz/mzk/editor/server/fedora/utils/.

Source file: BiblioModsUtils.java

  19 
vote

/** 
 * Gets the mods.
 * @param doc the doc
 * @return the mods
 */
public static ModsType getMods(org.w3c.dom.Document doc){
  try {
    JAXBContext jc=JAXBContext.newInstance("cz.mzk.editor.server.mods");
    Unmarshaller unmarshaller=jc.createUnmarshaller();
    JAXBElement<?> o=(JAXBElement<?>)unmarshaller.unmarshal(doc);
    if (o.getDeclaredType() == ModsType.class) {
      return (ModsType)o.getValue();
    }
  }
 catch (  JAXBException e) {
    LOGGER.error(e);
  }
  return null;
}
 

Example 25

From project mylyn.builds, under directory /org.eclipse.mylyn.hudson.core/src/org/eclipse/mylyn/internal/hudson/core/client/.

Source file: RestfulHudsonClient.java

  19 
vote

public static <T>T unmarshal(Node node,Class<T> clazz) throws JAXBException {
  JAXBContext ctx;
  try {
    ctx=JAXBContext.newInstance(clazz);
  }
 catch (  JAXBException e) {
    try {
      Class<?> contextBuilderClass=Class.forName("com.sun.xml.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder");
      Object obj=contextBuilderClass.newInstance();
      Method method=contextBuilderClass.getDeclaredMethod("setClasses",Class[].class);
      obj=method.invoke(obj,new Object[]{new Class[]{clazz}});
      method=contextBuilderClass.getDeclaredMethod("build");
      ctx=(JAXBContext)method.invoke(obj);
    }
 catch (    Exception e2) {
      throw new JAXBException(e2);
    }
  }
  Unmarshaller unmarshaller=ctx.createUnmarshaller();
  JAXBElement<T> hudsonElement=unmarshaller.unmarshal(node,clazz);
  return hudsonElement.getValue();
}
 

Example 26

From project onebusaway-nyc, under directory /onebusaway-nyc-transit-data-manager/onebusaway-nyc-tdm-adapters/src/main/java/org/onebusaway/nyc/transit_data_manager/adapters/api/processes/.

Source file: MtaBusDepotsToTcipXmlProcess.java

  19 
vote

private String generateXml(CptFleetSubsets inputElement) throws JAXBException {
  String outputStr=null;
  ObjectFactory tcipFinalObjectFactory=new ObjectFactory();
  JAXBElement<CptFleetSubsets> inputWrappedAsJaxbElement=tcipFinalObjectFactory.createCptFleetSubsets(inputElement);
  StringWriter wrtr=new StringWriter();
  JAXBContext jc=JAXBContext.newInstance(CptFleetSubsets.class);
  Marshaller m=jc.createMarshaller();
  m.setProperty("jaxb.formatted.output",new Boolean(true));
  m.marshal(inputWrappedAsJaxbElement,wrtr);
  outputStr=wrtr.toString();
  return outputStr;
}
 

Example 27

From project openengsb-framework, under directory /components/common/src/main/java/org/openengsb/core/common/remote/.

Source file: XmlMethodCallMarshalFilter.java

  19 
vote

private Document serializeResult(MethodResultMessage result){
  DOMResult domResult=new DOMResult();
  try {
    JAXBContext jaxbContext=JAXBContext.newInstance(MethodResultMessage.class,Class.forName(result.getResult().getClassName()));
    Marshaller marshaller=jaxbContext.createMarshaller();
    marshaller.marshal(new JAXBElement<MethodResultMessage>(new QName(MethodResultMessage.class.getSimpleName()),MethodResultMessage.class,result),domResult);
  }
 catch (  JAXBException e) {
    throw new FilterException(e);
  }
catch (  ClassNotFoundException e) {
    throw new FilterException(e);
  }
  return (Document)domResult.getNode();
}
 

Example 28

From project orbisgis-server, under directory /app/wms/src/main/java/org/orbisgis/server/wms/.

Source file: SLD.java

  19 
vote

private void init(StyledLayerDescriptorElement sldType) throws SeExceptions.InvalidStyle, WMSException {
  List<NamedLayerElement> sldLayers=sldType.getNamedLayer();
  this.layers=new ArrayList<SLDLayer>();
  for (  NamedLayerElement l : sldLayers) {
    String name=l.getName();
    SLDLayer sldLayer=new SLDLayer(name);
    JAXBElement<? extends AbstractStyleType> style=l.getAbstractStyle();
    if (style.getValue() instanceof StyleType) {
      StyleType se=(StyleType)style.getValue();
      sldLayer.addStyle(se);
    }
 else     if (style.getValue() instanceof StyleReferenceType) {
      StyleReferenceType seRef=(StyleReferenceType)style.getValue();
      OnlineResourceType seOR=seRef.getOnlineResource();
      String seHref=seOR.getHref();
      try {
        URI uri=new URI(seHref);
        Unmarshaller u=Services.JAXBCONTEXT.createUnmarshaller();
        JAXBElement<? extends AbstractStyleType> abstractStyle=(JAXBElement<? extends AbstractStyleType>)u.unmarshal(uri.toURL());
        StyleType se=(StyleType)abstractStyle.getValue();
        sldLayer.addStyle(se);
      }
 catch (      JAXBException jaxbException) {
        throw new WMSException(jaxbException);
      }
catch (      MalformedURLException malformedURLException) {
        throw new WMSException(malformedURLException);
      }
catch (      URISyntaxException ex) {
        throw new WMSException(ex);
      }
    }
    this.layers.add(sldLayer);
  }
}
 

Example 29

From project picketlink-idm, under directory /integration/deployer/src/main/java/org/picketlink/idm/integration/jboss5/.

Source file: JAXB2IdentityDeployerConfiguration.java

  19 
vote

@SuppressWarnings({"unchecked"}) public static PicketlinkIDMDeployerType createDeployerConfiguration(InputStream inputStream) throws Exception {
  if (inputStream == null) {
    throw new NullPointerException("deployer configuration is null");
  }
  JAXBElement<PicketlinkIDMDeployerType> deployerType=null;
  try {
    JAXBContext jaxbContext=JAXBContext.newInstance("org.picketlink.idm.integration.jboss5.jaxb2");
    Unmarshaller unMarshaller=jaxbContext.createUnmarshaller();
    deployerType=(JAXBElement<PicketlinkIDMDeployerType>)unMarshaller.unmarshal(inputStream);
  }
 catch (  JAXBException e) {
    logger.severe(e.getMessage());
    throw new IdentityConfigurationException("Cannot unmarshal idm deployer configuration: ",e);
  }
  if (deployerType != null) {
    return deployerType.getValue();
  }
  return null;
}
 

Example 30

From project picketlink-idm_1, under directory /integration/deployer/src/main/java/org/picketlink/idm/integration/jboss5/.

Source file: JAXB2IdentityDeployerConfiguration.java

  19 
vote

@SuppressWarnings({"unchecked"}) public static PicketlinkIDMDeployerType createDeployerConfiguration(InputStream inputStream) throws Exception {
  if (inputStream == null) {
    throw new NullPointerException("deployer configuration is null");
  }
  JAXBElement<PicketlinkIDMDeployerType> deployerType=null;
  try {
    JAXBContext jaxbContext=JAXBContext.newInstance("org.picketlink.idm.integration.jboss5.jaxb2");
    Unmarshaller unMarshaller=jaxbContext.createUnmarshaller();
    deployerType=(JAXBElement<PicketlinkIDMDeployerType>)unMarshaller.unmarshal(inputStream);
  }
 catch (  JAXBException e) {
    logger.severe(e.getMessage());
    throw new IdentityConfigurationException("Cannot unmarshal idm deployer configuration: ",e);
  }
  if (deployerType != null) {
    return deployerType.getValue();
  }
  return null;
}
 

Example 31

From project pluto, under directory /pluto-container/src/main/java/org/apache/pluto/container/impl/.

Source file: PortletAppDescriptorServiceImpl.java

  19 
vote

/** 
 * Read the Web Application Deployment Descriptor.
 * @return WebAppDD instance representing the descriptor.
 * @throws java.io.IOException
 */
public PortletApplicationDefinition read(String name,String contextPath,InputStream in) throws IOException {
  if (in == null) {
    throw new IOException("Cannot read from a null InputStream");
  }
  final XMLInputFactory xmlInputFactory=getXmlInputFactory();
  final XMLStreamReader streamReader;
  try {
    streamReader=xmlInputFactory.createXMLStreamReader(in);
  }
 catch (  XMLStreamException e) {
    final IOException ioe=new IOException(e.getLocalizedMessage());
    ioe.initCause(e);
    throw ioe;
  }
  final XMLStreamReader delegatingStreamReader=new NamespaceOverridingStreamReaderDelegate(streamReader);
  final JAXBElement<?> app;
  try {
    final Unmarshaller unmarshaller=this.jaxbContext.createUnmarshaller();
    unmarshaller.setEventHandler(new DefaultValidationEventHandler());
    app=(JAXBElement<?>)unmarshaller.unmarshal(delegatingStreamReader);
  }
 catch (  JAXBException e) {
    final IOException ioe=new IOException(e.getMessage());
    ioe.initCause(e);
    throw ioe;
  }
  PortletApplicationDefinition pad=null;
  if (app.getValue() instanceof org.apache.pluto.container.om.portlet10.impl.PortletAppType) {
    pad=((org.apache.pluto.container.om.portlet10.impl.PortletAppType)app.getValue()).upgrade();
  }
 else {
    pad=(PortletApplicationDefinition)app.getValue();
  }
  pad.setName(name);
  pad.setContextPath(contextPath);
  return pad;
}
 

Example 32

From project RegexTagForMusic, under directory /src/org/essembeh/rtfm/core/configuration/io/.

Source file: CoreConfigurationLoaderV1.java

  19 
vote

@Inject public CoreConfigurationLoaderV1(@Named("configuration.core") InputStream source) throws ConfigurationException {
  try {
    JAXBContext context=JAXBContext.newInstance("org.essembeh.rtfm.model.configuration.core.version1");
    Unmarshaller unmarshaller=context.createUnmarshaller();
    unmarshaller.setEventHandler(new DefaultValidationEventHandler());
    JAXBElement<TCoreConfigurationV1> root=unmarshaller.unmarshal(new StreamSource(source),TCoreConfigurationV1.class);
    model=root.getValue();
  }
 catch (  JAXBException e) {
    logger.info("Cannot load core configuration version 1: " + e.getMessage());
    throw new ConfigurationException(e.getMessage());
  }
}
 

Example 33

From project rhevm-api, under directory /common/jaxrs/src/main/java/com/redhat/rhevm/api/common/util/.

Source file: JAXBHelper.java

  19 
vote

/** 
 * It's unfortunate that's there's no clone already defined on JAXB generated classes. Here we emulate that missing deep copy support by marshalling and unmarshalling (a little heavyweight admittedly).
 * @param < S >    type parameter
 * @param object object to be cloned
 * @param clz    type of that object
 * @return       clone
 */
public static <S>S clone(JAXBElement<S> element){
  S ret=null;
  try {
    ByteArrayOutputStream baos=new ByteArrayOutputStream();
    marshall(baos,element);
    ret=unmarshall(new ByteArrayInputStream(baos.toString().getBytes()),element.getDeclaredType());
  }
 catch (  Exception e) {
  }
  return ret;
}