Java Code Examples for javax.xml.bind.JAXBException
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 Activiti-KickStart, under directory /activiti-kickstart-java/src/main/java/org/activiti/kickstart/service/.
Source file: KickstartServiceImpl.java

public KickstartWorkflow findWorkflowById(String id){ ProcessDefinition processDefinition=repositoryService.createProcessDefinitionQuery().processDefinitionId(id).singleResult(); InputStream is=null; Definitions definitions=null; try { is=repositoryService.getResourceAsStream(processDefinition.getDeploymentId(),processDefinition.getResourceName()); JAXBContext jc=JAXBContext.newInstance(Definitions.class); Unmarshaller um=jc.createUnmarshaller(); definitions=(Definitions)um.unmarshal(is); } catch ( JAXBException e) { throw new RuntimeException("Could not unmarshall workflow xml",e); } finally { IoUtil.closeSilently(is); } return transformationService.convertToKickstartWorkflow(definitions); }
Example 2
From project demonstrator-backend, under directory /demonstrator-backend-ejb/src/main/java/org/marssa/demonstrator/beans/.
Source file: DAQBean.java

@PostConstruct private void init() throws ConfigurationError, NoConnection, UnknownHostException, JAXBException, FileNotFoundException { logger.info("Initializing DAQ Bean"); JAXBContext context=JAXBContext.newInstance(new Class[]{Settings.class}); Unmarshaller unmarshaller=context.createUnmarshaller(); InputStream is=this.getClass().getClassLoader().getResourceAsStream("configuration/settings.xml"); Settings settings=(Settings)unmarshaller.unmarshal(is); for ( DAQType daq : settings.getDaqs().getDaq()) { AddressType addressElement=daq.getSocket(); MString address; if (addressElement.getHost().getIp() == null || addressElement.getHost().getIp().isEmpty()) { String hostname=addressElement.getHost().getHostname(); address=new MString(Inet4Address.getByName(hostname).getAddress().toString()); } else { address=new MString(addressElement.getHost().getIp()); } logger.info("Found configuration for {} connected to {}, port {}",new Object[]{daq.getDAQname(),address,addressElement.getPort()}); LabJack lj; switch (daq.getType()) { case LAB_JACK_U_3: lj=LabJackU3.getInstance(address,new MInteger(daq.getSocket().getPort())); break; case LAB_JACK_UE_9: lj=LabJackUE9.getInstance(address,new MInteger(daq.getSocket().getPort())); break; default : throw new ConfigurationError("Unknown DAQ type: " + daq.getType()); } daqs.put(address.toString() + ":" + addressElement.getPort(),lj); } logger.info("Initialized DAQ Bean"); }
Example 3
From project harmony, under directory /harmony.common.serviceinterface/src/main/java/org/opennaas/extensions/idb/serviceinterface/databinding/utils/.
Source file: JaxbSerializer.java

/** * 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 4
From project hbc-maven-core, under directory /src/main/java/org/hardisonbrewing/jaxb/.
Source file: JAXB.java

public static <T>T unmarshal(File file,Class<T> clazz) throws JAXBException { InputStream inputStream=null; try { inputStream=new FileInputStream(file); return unmarshal(inputStream,clazz); } catch ( Exception e) { throw new JAXBException(e); } finally { IOUtil.close(inputStream); } }
Example 5
From project commons-j, under directory /src/main/java/nerds/antelax/commons/xml/saxbp/.
Source file: ParseInterest.java

/** * Should be called only when the next event in the stream (either a Stax or JAXB event) is the event we are interested in. * @throws JAXBException */ void handleEvent(final Object event) throws JAXBException { Preconditions.checkNotNull(event); try { handlerMethod.invoke(handler,event); } catch ( final IllegalArgumentException iare) { throw new JAXBException("Unable to invoke handler method",iare); } catch ( final IllegalAccessException iace) { throw new JAXBException("Unable to invoke handler method",iace); } catch ( final InvocationTargetException ite) { throw new JAXBException("Unable to invoke handler method",ite); } }
Example 6
From project addis, under directory /application/src/main/java/org/drugis/addis/entities/.
Source file: DomainManager.java

/** * Replace the Domain by a new instance loaded from a XML stream (new format, .addis). * @param is XML stream to read objects from. * @param version Schema version the xml is in. * @throws IOException * @throws ClassNotFoundException */ public void loadXMLDomain(InputStream is,int version) throws IOException { try { AddisData data=JAXBHandler.unmarshallAddisData(JAXBConvertor.transformToLatest(is,version)); d_domain=(Domain)JAXBConvertor.convertAddisDataToDomain(data); is.close(); } catch ( JAXBException e) { throw new RuntimeException(e); } catch ( ConversionException e) { throw new RuntimeException(e); } catch ( TransformerException e) { throw new RuntimeException(e); } }
Example 7
From project Aion-Extreme, under directory /AE-go_DataPack/gameserver/data/scripts/system/handlers/admincommands/.
Source file: AdvSendFakeServerPacket.java

/** * {@inheritDoc} */ @Override public void executeCommand(final Player admin,String[] params){ if (params.length != 1) { PacketSendUtility.sendMessage(admin,"Example: //send [file] "); return; } final String mappingName=params[0]; final Player target=getTargetPlayer(admin); File packetsData=new File(FOLDER,mappingName + ".xml"); if (!packetsData.exists()) { PacketSendUtility.sendMessage(admin,"Mapping with name " + mappingName + " not found"); return; } final Packets packetsTemplate; try { packetsTemplate=(Packets)unmarshaller.unmarshal(packetsData); } catch ( JAXBException e) { logger.error("Unmarshalling error",e); return; } if (packetsTemplate.getPackets().isEmpty()) { PacketSendUtility.sendMessage(admin,"No packets to send."); return; } send(admin,target,packetsTemplate); }
Example 8
From project ALP, under directory /workspace/alp-reporter/src/main/java/com/lohika/alp/log4j/xml/.
Source file: XMLLayout.java

@Override public String format(LoggingEvent event){ try { xmlWriter.writeStartElement("event"); xmlWriter.writeAttribute("level",event.getLevel() + ""); xmlWriter.writeAttribute("thread",event.getThreadName()); xmlWriter.writeAttribute("logger",event.getLoggerName()); xmlWriter.writeAttribute("timestamp",event.getTimeStamp() + ""); Object message=event.getMessage(); if (isJAXBElement(message)) { try { marshaller.marshal(message,xmlWriter); } catch ( JAXBException e) { LogLog.error("XMLLayout error",e); } } else { xmlWriter.writeCharacters(message.toString() + "\r\n"); } String[] s=event.getThrowableStrRep(); StringBuffer sb=new StringBuffer(); if (s != null) { for (int i=0; i < s.length; i++) { sb.append(s[i]); sb.append("\r\n"); } xmlWriter.writeCharacters(sb.toString()); } xmlWriter.writeEndElement(); xmlWriter.writeCharacters("\r\n"); } catch ( XMLStreamException e) { LogLog.error("XMLLayout error",e); } return buffer.toString(); }
Example 9
From project ANNIS, under directory /annis-service/src/main/java/annis/.
Source file: AnnisRunner.java

public void doFind(String annisQuery){ List<Match> matches=annisDao.find(analyzeQuery(annisQuery,"find")); JAXBContext jc=null; try { jc=JAXBContext.newInstance(annis.service.objects.Match.class); } catch ( JAXBException ex) { log.error("Problems with writing XML",ex); } for (int i=0; i < matches.size(); i++) { try { jc.createMarshaller().marshal(matches.get(i),out); } catch ( JAXBException ex) { log.error("Problems with writing XML",ex); } out.println(); } }
Example 10
From project arquillian-rusheye, under directory /rusheye-impl/src/main/java/org/jboss/rusheye/result/writer/.
Source file: XmlResultWriter.java

private Marshaller createMarshaller() throws JAXBException { JAXBContext context=JAXBContext.newInstance("org.jboss.rusheye.suite"); Marshaller marshaller=context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true); return marshaller; }
Example 11
From project astyanax, under directory /src/main/java/com/netflix/astyanax/serializers/.
Source file: JaxbSerializer.java

/** * Constructor. * @param serializableClasses List of classes which can be serialized by this instance. Note that concrete classes directly referenced by any class in the list will also be serializable through this instance. */ public JaxbSerializer(final Class... serializableClasses){ marshaller=new ThreadLocal<Marshaller>(){ @Override protected Marshaller initialValue(){ try { return JAXBContext.newInstance(serializableClasses).createMarshaller(); } catch ( JAXBException e) { throw new IllegalArgumentException("Classes to serialize are not JAXB compatible.",e); } } } ; unmarshaller=new ThreadLocal<Unmarshaller>(){ @Override protected Unmarshaller initialValue(){ try { return JAXBContext.newInstance(serializableClasses).createUnmarshaller(); } catch ( JAXBException e) { throw new IllegalArgumentException("Classes to serialize are not JAXB compatible.",e); } } } ; }
Example 12
From project bdd-security, under directory /src/main/java/net/continuumsecurity/reporting/.
Source file: ScannerReporter.java

public void write(String reference,ScanIssueList issueList){ try { File f=new File(path); if (!f.exists()) { f.mkdirs(); } JAXBContext jaxbContext=new JAXBContextResolver().getContext(ScanIssueList.class); Marshaller marshaller=jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,new Boolean(true)); marshaller.marshal(issueList,new FileOutputStream(path + reference + ".xml")); } catch ( PropertyException e) { e.printStackTrace(); } catch ( JAXBException e) { e.printStackTrace(); } catch ( Exception e) { e.printStackTrace(); } }
Example 13
From project blog_1, under directory /miniprojects/generic-pojo-mappers/src/main/java/net/jakubholy/blog/genericmappers/xml/.
Source file: XmlElements.java

@SuppressWarnings("unchecked") private <T>T mapNodeToPojo(Node entryNode,Class<T> entryPojoType){ try { JAXBContext jaxb=JAXBContext.newInstance(entryPojoType); Unmarshaller unmarshaller=jaxb.createUnmarshaller(); unmarshaller.setListener(BEAN_VALIDATOR); unmarshaller.setEventHandler(new UnknownElementLoggingHandler()); return (T)unmarshaller.unmarshal(entryNode); } catch ( JAXBException e) { throw new RuntimeException("Mapping XML to Java Bean failed for " + entryPojoType.getName() + " and XML "+ xmlStart+ ": "+ e.getMessage(),e); } }
Example 14
From project blueprint-namespaces, under directory /blueprint/blueprint-annotation-impl/src/main/java/org/apache/aries/blueprint/annotation/impl/.
Source file: BlueprintAnnotationScannerImpl.java

public URL createBlueprintModel(Bundle bundle){ Tblueprint tblueprint=generateBlueprintModel(bundle); if (tblueprint != null) { BundleContext ctx=getBlueprintExtenderContext(); if (ctx == null) { ctx=bundle.getBundleContext(); } File dir=ctx.getDataFile(bundle.getSymbolicName() + "/" + bundle.getVersion()+ "/"); if (!dir.exists()) { dir.mkdirs(); } String blueprintPath=cachePath(bundle,"annotation-generated-blueprint.xml"); File file=ctx.getDataFile(blueprintPath); if (!file.exists()) { try { file.createNewFile(); } catch ( IOException e) { e.printStackTrace(); } } try { marshallOBRModel(tblueprint,file); } catch ( JAXBException e) { e.printStackTrace(); } try { return file.toURL(); } catch ( MalformedURLException e) { e.printStackTrace(); } } return null; }
Example 15
From project bpm-console, under directory /server/war/src/main/java/org/jboss/bpm/console/server/util/.
Source file: Payload2XML.java

public StringBuffer convert(String refId,Map<String,Object> javaPayload){ StringBuffer sb=new StringBuffer(); try { List<Class> clz=new ArrayList<Class>(javaPayload.size() + 2); clz.add(PayloadCollection.class); clz.add(PayloadEntry.class); List<PayloadEntry> data=new ArrayList<PayloadEntry>(); for ( String key : javaPayload.keySet()) { Object payload=javaPayload.get(key); clz.add(payload.getClass()); data.add(new PayloadEntry(key,payload)); } PayloadCollection dataset=new PayloadCollection(refId,data); JAXBContext jaxbContext=JAXBContext.newInstance(clz.toArray(new Class[]{})); ByteArrayOutputStream bout=new ByteArrayOutputStream(); Marshaller m=jaxbContext.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE); m.marshal(dataset,bout); sb.append(new String(bout.toByteArray())); } catch ( JAXBException e) { throw new RuntimeException("Payload2XML conversion failed",e); } return sb; }
Example 16
From project bundlemaker, under directory /_incubator/org.bundlemaker.core.exporter.structure101/src/org/bundlemaker/core/exporter/structure101/.
Source file: Structure101ExporterUtils.java

/** * <p> </p> * @param productsType * @param outputStream */ public static void marshal(DataType dataType,OutputStream outputStream){ try { JAXBContext jc=JAXBContext.newInstance(DataType.class,DependenciesType.class,DependencyType.class,ModulesType.class,ModuleType.class,ObjectFactory.class); Marshaller marshaller=jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true); marshaller.marshal(new ObjectFactory().createData(dataType),outputStream); } catch ( JAXBException e) { throw new RuntimeException(e.getMessage(),e); } }
Example 17
From project CampusLifePortlets, under directory /src/main/java/org/jasig/portlet/campuslife/athletics/dao/.
Source file: AthleticsDaoMockImpl.java

@Override public void afterPropertiesSet() throws Exception { try { JAXBContext jaxbContext=JAXBContext.newInstance(AthleticsFeed.class); Unmarshaller unmarshaller=jaxbContext.createUnmarshaller(); this.feed=(AthleticsFeed)unmarshaller.unmarshal(mockData.getInputStream()); } catch ( IOException e) { log.error("Failed to read mock data",e); } catch ( JAXBException e) { log.error("Failed to unmarshall mock data",e); } }
Example 18
From project catalog-api-client, under directory /client/src/main/java/com/shopzilla/api/service/.
Source file: ProductService.java

public ProductResponse xmlInputStreamToJava(InputStream in) throws IOException, JAXBException { try { ProductResponse productResponse=(ProductResponse)unmarshaller.unmarshal(new StreamSource(in)); System.out.println("productResponse = " + productResponse); return productResponse; } catch ( XmlMappingException xme) { xme.printStackTrace(); } return null; }
Example 19
From project CCR-Validator, under directory /src/main/java/org/openhealthdata/validation/.
Source file: CCRV1SchemaValidator.java

private void validate(StreamSource src){ ccr=null; try { validator.validate(src); Document xml=parseStreamSource(src,false); if (xml != null) { JAXBContext jc=JAXBContext.newInstance("org.astm.ccr"); Unmarshaller um=jc.createUnmarshaller(); ccr=(ContinuityOfCareRecord)um.unmarshal(xml); } } catch ( SAXException e) { logger.log(Level.SEVERE,"Not Valid CCR XML: " + e.getMessage()); } catch ( IOException e) { logger.log(Level.SEVERE,"Exception during validating",e); e.printStackTrace(); } catch ( JAXBException e) { logger.log(Level.SEVERE,"Exception during unmarshalling XML DOM",e); e.printStackTrace(); } }
Example 20
From project cdk, under directory /generator/src/main/java/org/richfaces/cdk/xmlconfig/.
Source file: JAXBBinding.java

@SuppressWarnings("unchecked") <T>T unmarshal(String schemaLocation,Class<T> bindClass,InputSource inputSource) throws CdkException { T unmarshal=null; try { XMLReader xmlReader=XMLReaderFactory.createXMLReader(); xmlReader.setEntityResolver(resolver); xmlReader.setFeature("http://xml.org/sax/features/validation",true); xmlReader.setFeature("http://apache.org/xml/features/validation/schema",true); xmlReader.setFeature("http://apache.org/xml/features/validation/dynamic",true); Unmarshaller u=JAXBContext.newInstance(bindClass).createUnmarshaller(); u.setEventHandler(new ValidationEventCollector()); XIncludeTransformer xIncludeTransformer=new XIncludeTransformer(log); if (null != inputSource.getSystemId()) { xIncludeTransformer.setBaseUri(new URI(inputSource.getSystemId())); } UnmarshallerHandler unmarshallerHandler=u.getUnmarshallerHandler(); xIncludeTransformer.setContentHandler(unmarshallerHandler); xIncludeTransformer.setResolver(resolver); xmlReader.setContentHandler(xIncludeTransformer); xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler",xIncludeTransformer); xmlReader.parse(inputSource); unmarshal=(T)unmarshallerHandler.getResult(); } catch ( JAXBException e) { throw new CdkException("JAXB Unmarshaller error: " + e.getMessage(),e); } catch ( URISyntaxException e) { throw new CdkException("Invalid XML source URI: " + e.getMessage(),e); } catch ( IOException e) { throw new CdkException("JAXB Unmarshaller input error: " + e.getMessage(),e); } catch ( SAXException e) { throw new CdkException("XML error: " + e.getMessage(),e); } finally { } return unmarshal; }
Example 21
From project chargifyService, under directory /src/main/java/com/mondora/chargify/controller/.
Source file: Chargify.java

protected Object parse(Class clazz,InputStream inputStream) throws ChargifyException { byte[] in=null; try { JAXBContext context=JAXBContext.newInstance(clazz); Unmarshaller unmarshaller=context.createUnmarshaller(); unmarshaller.setSchema(null); if (logger.isTraceEnabled()) { try { in=readByteStream(inputStream); logger.trace("Response input " + new String(in)); inputStream=new ByteArrayInputStream(in); } catch ( IOException e) { } } Object xmlObject=clazz.cast(unmarshaller.unmarshal(inputStream)); return xmlObject; } catch ( JAXBException e) { if (logger.isTraceEnabled()) logger.trace(e.getMessage(),e); if (logger.isInfoEnabled()) logger.info(e.getMessage()); throw new ChargifyException("Unparsable Entity " + new String(in)); } }
Example 22
public static void main(String[] args){ try { Smil smil=Parser.unmarshal(new File("resc/sample.smil")); System.out.print('d'); Parser.marshal(smil,new File("out.smil")); } catch ( JAXBException e) { e.printStackTrace(); } }
Example 23
From project cloudify, under directory /esc/src/main/java/org/cloudifysource/esc/driver/provisioning/azure/client/.
Source file: MicrosoftAzureModelUtils.java

/** * @param body - the object to marshal * @param network - whether or not this object belongs to the network domain model. * @return - a String representation in the form of an XML of the body * @throws MicrosoftAzureException - indicates a marshaling exception happened */ public static String marshall(final Object body,final boolean network) throws MicrosoftAzureException { JAXBContext context=ModelContextFactory.createInstance(); StringWriter sw=new StringWriter(); Marshaller m; try { m=context.createMarshaller(); m.marshal(body,sw); Document doc=createEmptyDocument(); m.marshal(body,doc); String xml=getStringFromDocument(doc); if (network) { xml=addNameSpaceToRootElement(xml,"http://schemas.microsoft.com/ServiceHosting/2011/07/NetworkConfiguration"); } else { xml=addNameSpaceToRootElement(xml,"http://schemas.microsoft.com/windowsazure"); } return xml; } catch ( JAXBException e) { throw new MicrosoftAzureException(e); } }
Example 24
From project cogroo4, under directory /cogroo-ann/src/main/java/org/cogroo/config/.
Source file: LanguageConfigurationUtil.java

/** * Creates a {@link LanguageConfiguration} from a {@link InputStream}, which remains opened. * @param configuration the input stream * @return a {@link LanguageConfiguration} */ public static LanguageConfiguration get(InputStream configuration){ try { return unmarshal(configuration); } catch ( JAXBException e) { throw new InitializationException("Invalid configuration file.",e); } }
Example 25
From project com.cedarsoft.serialization, under directory /test/performance/src/test/java/com/cedarsoft/serialization/test/performance/.
Source file: JaxbTest.java

@Test public void testSimple() throws JAXBException, IOException, SAXException { FileType type=new FileType("jpg",new Extension(".","jpg",true),false); Marshaller marshaller=context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true); ByteArrayOutputStream out=new ByteArrayOutputStream(); marshaller.marshal(type,out); AssertUtils.assertXMLEquals(out.toString(),"<ns2:fileType xmlns:ns2=\"http://test.cedarsoft.com/fileType\">\n" + " <dependent>false</dependent>\n" + " <extension>\n"+ " <default>true</default>\n"+ " <delimiter>.</delimiter>\n"+ " <extension>jpg</extension>\n"+ " </extension>\n"+ " <id>jpg</id>\n"+ "</ns2:fileType>"); }
Example 26
From project components, under directory /camel/camel-core/src/main/java/org/switchyard/component/camel/config/model/v1/.
Source file: V1CamelImplementationModel.java

private static JAXBContext createJAXBInstance(){ try { return JAXBContext.newInstance(Constants.JAXB_CONTEXT_PACKAGES); } catch ( JAXBException e) { throw new SwitchYardException(e); } }
Example 27
From project core_1, under directory /transform/src/main/java/org/switchyard/transform/jaxb/internal/.
Source file: JAXBMarshalTransformer.java

/** * Public constructor. * @param from From type. * @param to To type. * @param contextPath JAXB context path (Java package). * @throws SwitchYardException Failed to create JAXBContext. */ public JAXBMarshalTransformer(QName from,QName to,String contextPath) throws SwitchYardException { super(from,to); try { if (contextPath != null) { _jaxbContext=JAXBContext.newInstance(contextPath); } else { _jaxbContext=JAXBContext.newInstance(QNameUtil.toJavaMessageType(from)); } } catch ( JAXBException e) { throw new SwitchYardException("Failed to create JAXBContext for '" + from + "'.",e); } }
Example 28
From project CoursesPortlet, under directory /courses-portlet-webapp/src/main/java/org/jasig/portlet/courses/dao/xml/.
Source file: MockCoursesDaoImpl.java

@Override public void afterPropertiesSet() throws Exception { try { JAXBContext jaxbContext=JAXBContext.newInstance(TermsAndCourses.class); Unmarshaller unmarshaller=jaxbContext.createUnmarshaller(); this.summary=(TermsAndCourses)unmarshaller.unmarshal(mockData.getInputStream()); } catch ( IOException e) { log.error("Failed to read mock data",e); } catch ( JAXBException e) { log.error("Failed to unmarshall mock data",e); } }
Example 29
From project crest, under directory /core/src/main/java/org/codegist/crest/serializer/jaxb/.
Source file: JaxbFactory.java

static Jaxb create(CRestConfig crestConfig,Class<?> source) throws JAXBException { String prefix=source.getName(); Jaxb jaxb=crestConfig.get(prefix + JAXB); if (jaxb != null) { return jaxb; } String modelPackage=crestConfig.get(prefix + MODEL_PACKAGE); if (modelPackage != null) { return create(crestConfig,source,modelPackage); } Class<?> modelFactory=crestConfig.get(prefix + MODEL_FACTORY_CLASS); if (modelFactory != null) { return create(crestConfig,source,modelFactory); } return new TypeCachingJaxb(crestConfig,source); }
Example 30
From project dev-examples, under directory /input-demo/src/main/java/org/richfaces/demo/.
Source file: CountriesBean.java

@PostConstruct public void initialize(){ try { JAXBContext countryContext=JAXBContext.newInstance(Countries.class); Unmarshaller unmarshaller=countryContext.createUnmarshaller(); ClassLoader classLoader=Thread.currentThread().getContextClassLoader(); URL dataUrl=classLoader.getResource("org/richfaces/demo/countries.xml"); countries=((Countries)unmarshaller.unmarshal(dataUrl)).getCountries(); } catch ( JAXBException e) { throw new FacesException(e.getMessage(),e); } }
Example 31
From project drools-chance, under directory /drools-pmml/src/main/java/org/drools/pmml_4_1/.
Source file: PMML4Compiler.java

/** * Imports a PMML source file, returning a Java descriptor * @param model the PMML package name (classes derived from a specific schema) * @param source the name of the PMML resource storing the predictive model * @return the Java Descriptor of the PMML resource */ public PMML loadModel(String model,InputStream source){ try { JAXBContext jc=JAXBContext.newInstance(model); Unmarshaller unmarshaller=jc.createUnmarshaller(); return (PMML)unmarshaller.unmarshal(source); } catch ( JAXBException e) { e.printStackTrace(); return null; } }
Example 32
From project droolsjbpm-integration, under directory /drools-camel/src/test/java/org/drools/camel/component/.
Source file: JaxbTest.java

private JAXBContext getJaxbContext() throws JAXBException { List<String> classesName=new ArrayList(); classesName.add("org.drools.pipeline.camel.Person"); Set<String> set=new HashSet<String>(); for ( String clsName : DroolsJaxbHelperProviderImpl.JAXB_ANNOTATED_CMD) { set.add(clsName.substring(0,clsName.lastIndexOf('.'))); } for ( String clsName : classesName) { set.add(clsName.substring(0,clsName.lastIndexOf('.'))); } StringBuilder sb=new StringBuilder(); for ( String pkgName : set) { sb.append(pkgName); sb.append(':'); } System.out.println("context path: " + sb.toString()); return JAXBContext.newInstance(sb.toString()); }
Example 33
From project ds-annotation-builder, under directory /com.wuetherich.osgi.ds.annotations/src/com/wuetherich/osgi/ds/annotations/internal/.
Source file: AbstractComponentDescription.java

/** * <p> </p> * @param xmlProjectDescription * @param outputStream */ public String toXml(){ try { JAXBContext jaxbContext=createJAXBContext(); Marshaller marshaller=jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true); StringWriter result=new StringWriter(); marshaller.marshal(new ObjectFactory().createComponent(_tcomponent),result); return result.toString(); } catch ( JAXBException e) { e.printStackTrace(); throw new RuntimeException(e.getMessage(),e); } }
Example 34
From project Easy-Cassandra, under directory /src/main/java/org/easycassandra/util/.
Source file: DomUtil.java

/** * Create a Object from XML Document * @param file - a XML Document * @param objClass - * @return the Object */ public static Object getDom(File file,@SuppressWarnings("rawtypes") Class objClass){ try { JAXBContext jAXBContext=JAXBContext.newInstance(objClass); Unmarshaller unmarshaller=jAXBContext.createUnmarshaller(); return unmarshaller.unmarshal(file); } catch ( JAXBException exception) { file.delete(); Logger.getLogger(DomUtil.class.getName()).log(Level.SEVERE,null,exception); } return null; }
Example 35
From project faces, under directory /Proyectos/richfaces4-iteration/src/main/java/pe/joedayz/ejemplos/demo/util/.
Source file: GamesParser.java

public synchronized List<GameDescriptor> getGameDescriptorsList(){ if (gamesList == null) { ClassLoader ccl=Thread.currentThread().getContextClassLoader(); URL resource=ccl.getResource("games.xml"); JAXBContext context; try { context=JAXBContext.newInstance(GameDescriptorsHolder.class); GameDescriptorsHolder gamesHolder=(GameDescriptorsHolder)context.createUnmarshaller().unmarshal(resource); gamesList=gamesHolder.getGameDescriptors(); } catch ( JAXBException e) { throw new FacesException(e.getMessage(),e); } } return gamesList; }
Example 36
From project fed4j, under directory /src/main/java/com/jute/fed4j/example/response/yahoo/.
Source file: WebSearchResponse.java

public void unmarshal(InputStream in){ if (jaxbContext == null) { return; } try { Unmarshaller unmarshaller=jaxbContext.createUnmarshaller(); unmarshaller.setSchema(null); result=(ResultSet)unmarshaller.unmarshal(new InputSource(new StringReader(body))); } catch ( JAXBException e) { log.error("Failed to unmarshal WebSearch Response",e); } }
Example 37
From project fedora-client, under directory /fedora-client-core/src/main/java/com/yourmediashelf/fedora/client/response/.
Source file: FedoraResponseImpl.java

/** * Unmarshall the Fedora ClientResponse using the JAXB schema-generated classes (see: target/generated-sources/). * @param contextPath JAXB contextPath * @return the unmarshalled XML * @throws FedoraClientException */ public Object unmarshallResponse(ContextPath contextPath) throws FedoraClientException { Object response=null; Schema schema=null; if (validateSchema()) { try { SchemaFactory schemaFactory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); schema=schemaFactory.newSchema(); } catch ( SAXException e) { throw new FedoraClientException(e.getMessage(),e); } } try { JAXBContext context=JAXBContext.newInstance(contextPath.path()); Unmarshaller unmarshaller=context.createUnmarshaller(); unmarshaller.setSchema(schema); response=unmarshaller.unmarshal(new BufferedReader(new InputStreamReader(getEntityInputStream()))); } catch ( JAXBException e) { throw new FedoraClientException(e.getMessage(),e); } return response; }
Example 38
From project flip, under directory /core/src/main/java/com/tacitknowledge/flip/properties/.
Source file: XmlPropertyReader.java

/** * {@inheritDoc } */ @Override protected void readDescriptors(){ try { final InputStream in=getConfigurationStream(getConfig()); if (in == null) { return; } final JAXBContext context=JAXBContext.newInstance(FeatureDescriptors.class); final Unmarshaller unmarshaller=context.createUnmarshaller(); final FeatureDescriptors descriptors=(FeatureDescriptors)unmarshaller.unmarshal(in); cache.clear(); if (descriptors != null && descriptors.getFeatures() != null) { for ( final FeatureDescriptor descriptor : descriptors.getFeatures()) { cache.put(descriptor.getName(),descriptor); } } } catch ( final JAXBException ex) { Logger.getLogger(XmlPropertyReader.class.getName()).log(Level.WARNING,null,ex); } }
Example 39
From project gedcomx, under directory /enunciate-gedcomx-support/src/main/java/org/gedcomx/build/enunciate/rdf/.
Source file: RDFProcessor.java

protected void loadKnownRDFSchemaDescriptions(){ Unmarshaller unmarshaller; try { unmarshaller=JAXBContext.newInstance(RDFSchema.class).createUnmarshaller(); } catch ( JAXBException e) { throw new RuntimeException(e); } URL resource=RDFProcessor.class.getResource("dcterms.rdf.xml"); if (resource != null) { loadRDFSchema(unmarshaller,resource); } addDescription(RDFSchema.RDF_NAMESPACE,"ID",true,true); addDescription(RDFSchema.RDF_NAMESPACE,"about",true,true); addDescription(RDFSchema.RDF_NAMESPACE,"resource",true,true); addDescription(RDFSchema.RDF_NAMESPACE,"value",true,true); addDescription(RDFSchema.RDF_NAMESPACE,"type",true,false); addDescription(RDFSchema.RDF_NAMESPACE,"Description",true,false); addDescription(XMLConstants.XML_NS_URI,"lang",true,true); }
Example 40
From project geolatte-maprenderer, under directory /src/main/java/org/geolatte/maprenderer/sld/.
Source file: SLD.java

private SLD(){ try { ctxt=JAXBContext.newInstance("net.opengis.sld.v_1_1_0:net.opengis.wms.v_1_3_0"); objectFactory=new ObjectFactory(); } catch ( JAXBException e) { throw new IllegalStateException("Can't instantiate SLD static factory",e); } }
Example 41
From project geolatte-mapserver, under directory /src/main/java/org/geolatte/mapserver/wms/.
Source file: JAXB.java

private JAXB(){ try { ctxt=JAXBContext.newInstance("net.opengis.wms.v_1_1_1"); objectFactory=new ObjectFactory(); } catch ( JAXBException e) { throw new IllegalStateException("Can't instantiate JAXB static factory",e); } }
Example 42
From project geronimo-jaspi, under directory /geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/.
Source file: AuthConfigFactoryImpl.java

private void loadConfig(){ if (configFile != null && configFile.length() > 0) { JaspiType jaspiType; try { FileReader in=new FileReader(configFile); try { jaspiType=JaspiXmlUtil.loadJaspi(in); } finally { in.close(); } } catch ( ParserConfigurationException e) { throw new SecurityException("Could not read config",e); } catch ( IOException e) { throw new SecurityException("Could not read config",e); } catch ( SAXException e) { throw new SecurityException("Could not read config",e); } catch ( JAXBException e) { throw new SecurityException("Could not read config",e); } catch ( XMLStreamException e) { throw new SecurityException("Could not read config",e); } initialize(jaspiType); } }
Example 43
From project gmc, under directory /src/org.gluster.storage.management.gateway/src/org/gluster/storage/management/gateway/utils/.
Source file: ServerUtil.java

/** * Unmarshals given input string into object of given class * @param expectedClass Class whose object is expected * @param input Input string * @return Object of given expected class */ public <T>T unmarshal(Class<T> expectedClass,String input){ try { JAXBContext context=JAXBContext.newInstance(expectedClass); Unmarshaller um=context.createUnmarshaller(); return (T)um.unmarshal(new ByteArrayInputStream(input.getBytes())); } catch ( JAXBException e) { String errMsg="Error during unmarshalling string [" + input + "] for class ["+ expectedClass.getName()+ ": ["+ e.getMessage()+ "]"; logger.error(errMsg,e); throw new GlusterRuntimeException(errMsg,e); } }
Example 44
From project GNDMS, under directory /model/src/de/zib/gndms/c3resource/.
Source file: C3ResourceReader.java

public C3ResourceReader(){ try { context=JAXBContext.newInstance("de.zib.gndms.c3resource.jaxb"); evFactory=XMLEventFactory.newInstance(); inFactory=XMLInputFactory.newInstance(); outFactory=XMLOutputFactory.newInstance(); unmarshaller=context.createUnmarshaller(); unmarshaller.setSchema(null); } catch ( JAXBException jxe) { throw new RuntimeException("Failed to initialize C3ResourceReader",jxe); } }
Example 45
From project GoFleetLSServer, under directory /backtrackTSP/src/main/java/org/emergya/backtrackTSP/.
Source file: DistanceMatrix.java

private Double calculateDistance(TSPStop from,TSPStop to,Key k) throws InterruptedException { String host_port="localhost:5000"; String http="http"; if (configuration != null) { if (configuration.get("OSRM_SSL","off").equals("on")) http="https"; host_port=configuration.get("OSRM_HOST","localhost:5000"); } DetermineRouteRequestType param=new DetermineRouteRequestType(); if (param.getRoutePlan() == null) param.setRoutePlan(new RoutePlanType()); if (param.getRoutePlan().getWayPointList() == null) param.getRoutePlan().setWayPointList(new WayPointListType()); WayPointListType waypointList=param.getRoutePlan().getWayPointList(); WayPointType start=getWayPoint(from.getPosition()); WayPointType end=getWayPoint(to.getPosition()); waypointList.setStartPoint(start); waypointList.setEndPoint(end); try { DetermineRouteResponseType res=(DetermineRouteResponseType)osrm.routePlan(param,host_port,http,Locale.ROOT); double cost=res.getRouteSummary().getTotalDistance().getValue().doubleValue(); synchronized (distances) { distances.put(k,cost); } return cost; } catch ( IOException e) { LOG.error("Error extracting distance from " + from + " to "+ to); return Double.MAX_VALUE; } catch ( ParseException e) { LOG.error("Error extracting distance from " + from + " to "+ to); return Double.MAX_VALUE; } catch ( JAXBException e) { LOG.error("Error extracting distance from " + from + " to "+ to); return Double.MAX_VALUE; } }
Example 46
From project ha-jdbc, under directory /src/main/java/net/sf/hajdbc/xml/.
Source file: XMLDatabaseClusterConfigurationFactory.java

/** * {@inheritDoc} * @see net.sf.hajdbc.DatabaseClusterConfigurationFactory#createConfiguration() */ @Override public DatabaseClusterConfiguration<Z,D> createConfiguration() throws SQLException { logger.log(Level.INFO,Messages.HA_JDBC_INIT.getMessage(),Version.getVersion(),this.streamFactory); try { SchemaFactory schemaFactory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema=schemaFactory.newSchema(SCHEMA); Unmarshaller unmarshaller=JAXBContext.newInstance(this.targetClass).createUnmarshaller(); unmarshaller.setSchema(schema); XMLReader reader=new PropertyReplacementFilter(XMLReaderFactory.createXMLReader()); InputSource source=SAXSource.sourceToInputSource(this.streamFactory.createSource()); return this.targetClass.cast(unmarshaller.unmarshal(new SAXSource(reader,source))); } catch ( JAXBException e) { throw new SQLException(e); } catch ( SAXException e) { throw new SQLException(e); } }
Example 47
From project hackergarten-moreunit, under directory /org.moreunit.mock/src/org/moreunit/mock/templates/.
Source file: XmlTemplateDefinitionReader.java

public MockingTemplates read(InputStream is) throws MockingTemplateException { try { JAXBContext jc=JAXBContext.newInstance(MockingTemplates.class); Unmarshaller unmarshaller=jc.createUnmarshaller(); return (MockingTemplates)unmarshaller.unmarshal(is); } catch ( JAXBException e) { throw new MockingTemplateException("Could not read XML definition",e); } }
Example 48
From project hibernate-metamodelgen, under directory /src/main/java/org/hibernate/jpamodelgen/xml/.
Source file: XmlParser.java

/** * Tries to open the specified xml file and return an instance of the specified class using JAXB. * @param resource the xml file name * @param clazz The type of jaxb node to return * @param schemaName The schema to validate against (can be {@code null}); * @return The top level jaxb instance contained in the xml file or {@code null} in case the file could not be foundor could not be unmarshalled. */ private <T>T parseXml(String resource,Class<T> clazz,String schemaName){ InputStream stream=getInputStreamForResource(resource); if (stream == null) { context.logMessage(Diagnostic.Kind.OTHER,resource + " not found."); return null; } try { JAXBContext jc=JAXBContext.newInstance(ObjectFactory.class); Unmarshaller unmarshaller=jc.createUnmarshaller(); if (schemaName != null) { unmarshaller.setSchema(getSchema(schemaName)); } return clazz.cast(unmarshaller.unmarshal(stream)); } catch ( JAXBException e) { String message="Error unmarshalling " + resource + " with exception :\n "+ e; context.logMessage(Diagnostic.Kind.WARNING,message); return null; } catch ( Exception e) { String message="Error reading " + resource + " with exception :\n "+ e; context.logMessage(Diagnostic.Kind.WARNING,message); return null; } }
Example 49
From project hibernate-validator, under directory /engine/src/main/java/org/hibernate/validator/internal/xml/.
Source file: ValidationXmlParser.java

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 50
From project hqapi, under directory /hqapi1/src/main/java/org/hyperic/hq/hqapi1/.
Source file: HQConnection.java

/** * Issue a POST against the API. * @param path The web service endpoint * @param o The object to POST. This object will be serialized into XMLprior to being sent. * @param responseHandler The {@link org.hyperic.hq.hqapi1.ResponseHandler} to handle this response. * @return The response object from the operation. This response will be ofthe type given in the responseHandler argument. * @throws IOException If a network error occurs during the request. */ public <T>T doPost(String path,Object o,ResponseHandler<T> responseHandler) throws IOException { HttpPost post=new HttpPost(); ByteArrayOutputStream bos=new ByteArrayOutputStream(); try { XmlUtil.serialize(o,bos,Boolean.FALSE); } catch ( JAXBException e) { ServiceError error=new ServiceError(); error.setErrorCode("UnexpectedError"); error.setReasonText("Unable to serialize response"); if (_log.isDebugEnabled()) { _log.debug("Unable to serialize response",e); } return responseHandler.getErrorResponse(error); } MultipartEntity multipartEntity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntity.addPart("postdata",new StringBody(bos.toString("UTF-8"),Charset.forName("UTF-8"))); post.setEntity(multipartEntity); return runMethod(post,path,responseHandler); }
Example 51
From project httpobjects, under directory /core/src/main/java/org/httpobjects/representation/.
Source file: JaxbXmlRepresentation.java

@Override public void write(OutputStream out){ try { jaxb.createMarshaller().marshal(obj,out); } catch ( JAXBException e) { throw new RuntimeException(e); } }
Example 52
From project interoperability-framework, under directory /toolwrapper/src/test/java/eu/impact_project/iif/tw/gen/.
Source file: ToolspecValidatorTest.java

private ToolspecValidator getToolspecValidator(String toospecXml) throws GeneratorException { ToolspecValidator tv; try { Configuration ioc=new Configuration(); ioc.setXmlConf(new File(Constants.DEFAULT_TOOLSPEC)); ioc.setProjConf(new File(Constants.DEFAULT_PROJECT_PROPERTIES)); JAXBContext context; context=JAXBContext.newInstance("eu.impact_project.iif.tw.toolspec"); Unmarshaller unmarshaller=context.createUnmarshaller(); Toolspec toolspec=(Toolspec)unmarshaller.unmarshal(new File(ioc.getXmlConf())); tv=new ToolspecValidator(toolspec,ioc); return tv; } catch ( JAXBException ex) { logger.error("JAXBException",ex); throw new GeneratorException("JAXBException occurred."); } }
Example 53
From project Ivory, under directory /client/src/main/java/org/apache/ivory/entity/v0/.
Source file: EntityType.java

public Unmarshaller getUnmarshaller() throws JAXBException { Unmarshaller unmarshaller=jaxbContext.createUnmarshaller(); unmarshaller.setSchema(schema); unmarshaller.setEventHandler(new EventHandler()); return unmarshaller; }