List of usage examples for javax.xml.bind Unmarshaller setSchema
public void setSchema(javax.xml.validation.Schema schema);
From source file:org.ff4j.console.conf.XmlConfigurationParser.java
/** * Mthode permettant de crer le Unmarshaller pour le parsing du XML. * @param modelPackage/*from www.j a v a2s. com*/ * nom du package qui contient les beans utilises pour le parsing du fichier. * @param schemafile * le fichier XSD pour la validation du XML. * @return Unmarshaller * @throws JAXBException * @throws SAXException */ public Unmarshaller getUnmarshaller(String modelPackage, InputStream schemaStream) throws JAXBException, SAXException { JAXBContext jc = JAXBContext.newInstance(modelPackage); SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); Schema schema = sf.newSchema(new StreamSource(schemaStream)); Unmarshaller u = jc.createUnmarshaller(); u.setSchema(schema); u.setEventHandler(new XmlConfigurationErrorHandler()); return u; }
From source file:org.apache.taverna.scufl2.translator.t2flow.defaultactivities.AbstractActivityParser.java
public <ConfigType> ConfigType unmarshallXml(T2FlowParser t2FlowParser, String xml, Class<ConfigType> configType) throws ReaderException { Unmarshaller unmarshaller2 = t2FlowParser.getUnmarshaller(); unmarshaller2.setSchema(null); Source source = new StreamSource(new StringReader(xml)); try {/* w w w. j a va2 s. c om*/ JAXBElement<ConfigType> configElemElem = unmarshaller2.unmarshal(source, configType); return configElemElem.getValue(); } catch (JAXBException | ClassCastException e) { throw new ReaderException("Can't parse xml " + xml, e); } }
From source file:com.agimatec.validation.jsr303.xml.ValidationParser.java
private ValidationConfigType parseXmlConfig() { try {//from ww w .j a va2 s .c o m InputStream inputStream = getInputStream(validationXmlFile); if (inputStream == null) { if (log.isDebugEnabled()) log.debug("No " + validationXmlFile + " found. Using annotation based configuration only."); return null; } if (log.isDebugEnabled()) log.debug(validationXmlFile + " found."); Schema schema = getSchema(); 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 new ValidationException("Unable to parse " + validationXmlFile, e); } catch (IOException e) { throw new ValidationException("Unable to parse " + validationXmlFile, e); } }
From source file:de.thorstenberger.taskmodel.complex.complextaskdef.impl.ComplexTaskDefDAOImpl.java
public ComplexTaskDefRoot getComplexTaskDefRoot(InputStream complexTaskIS) throws TaskApiException { ComplexTaskDef complexTask;/*from ww w. j a v a 2s .c o m*/ JAXBContext jc = createJAXBContext(); Unmarshaller unmarshaller = null; try { unmarshaller = JAXBUtils.getJAXBUnmarshaller(jc); // enable validation unmarshaller.setSchema(JAXB2Validation.loadSchema("complexTaskDef.xsd")); BufferedInputStream bis = new BufferedInputStream(complexTaskIS); complexTask = (ComplexTaskDef) unmarshaller.unmarshal(bis); bis.close(); } catch (JAXBException e1) { throw new TaskModelPersistenceException(e1); } catch (IOException e2) { throw new TaskModelPersistenceException(e2); } finally { if (unmarshaller != null) JAXBUtils.releaseJAXBUnmarshaller(jc, unmarshaller); } return new ComplexTaskDefRootImpl(complexTask, complexTaskFactory); }
From source file:de.intevation.test.irixservice.UploadReportTest.java
public ReportType getReportFromFile(String file) { try {/*from w w w . j a va 2s.c o m*/ JAXBContext jaxbContext = JAXBContext.newInstance(ReportType.class.getPackage().getName()); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(testObj.irixSchemaFile); Unmarshaller u = jaxbContext.createUnmarshaller(); u.setSchema(schema); JAXBElement obj = (JAXBElement) u.unmarshal(new File(file)); return (ReportType) obj.getValue(); } catch (JAXBException | SAXException e) { log.debug("Failed to parse report test data: " + file); log.debug(e); return null; } }
From source file:admincommands.Reload.java
@Override public void executeCommand(Player admin, String[] params) { if (admin.getAccessLevel() < AdminConfig.COMMAND_RELOAD) { PacketSendUtility.sendMessage(admin, "You dont have enough rights to execute this command"); return;/* w w w. ja v a2 s.c o m*/ } if (params == null || params.length != 1) { PacketSendUtility.sendMessage(admin, "syntax //reload <quest | skill | portal | spawn | admcmd>"); return; } if (params[0].equals("quest")) { File xml = new File("./data/static_data/quest_data/quest_data.xml"); File dir = new File("./data/static_data/quest_script_data"); try { QuestEngine.getInstance().shutdown(); JAXBContext jc = JAXBContext.newInstance(StaticData.class); Unmarshaller un = jc.createUnmarshaller(); un.setSchema(getSchema("./data/static_data/static_data.xsd")); QuestsData newQuestData = (QuestsData) un.unmarshal(xml); QuestsData questsData = DataManager.QUEST_DATA; questsData.setQuestsData(newQuestData.getQuestsData()); QuestScriptsData questScriptsData = DataManager.QUEST_SCRIPTS_DATA; questScriptsData.getData().clear(); for (File file : listFiles(dir, true)) { QuestScriptsData data = ((QuestScriptsData) un.unmarshal(file)); if (data != null) if (data.getData() != null) questScriptsData.getData().addAll(data.getData()); } QuestEngine.getInstance().load(); } catch (Exception e) { PacketSendUtility.sendMessage(admin, "Quests reload failed!"); log.error(e); } finally { PacketSendUtility.sendMessage(admin, "Quests reloaded successfuly!"); } } else if (params[0].equals("skill")) { File dir = new File("./data/static_data/skills"); try { JAXBContext jc = JAXBContext.newInstance(StaticData.class); Unmarshaller un = jc.createUnmarshaller(); un.setSchema(getSchema("./data/static_data/static_data.xsd")); List<SkillTemplate> newTemplates = new ArrayList<SkillTemplate>(); for (File file : listFiles(dir, true)) { SkillData data = (SkillData) un.unmarshal(file); if (data != null) newTemplates.addAll(data.getSkillTemplates()); } DataManager.SKILL_DATA.setSkillTemplates(newTemplates); } catch (Exception e) { PacketSendUtility.sendMessage(admin, "Skills reload failed!"); log.error(e); } finally { PacketSendUtility.sendMessage(admin, "Skills reloaded successfuly!"); } } else if (params[0].equals("portal")) { File dir = new File("./data/static_data/portals"); try { JAXBContext jc = JAXBContext.newInstance(StaticData.class); Unmarshaller un = jc.createUnmarshaller(); un.setSchema(getSchema("./data/static_data/static_data.xsd")); List<PortalTemplate> newTemplates = new ArrayList<PortalTemplate>(); for (File file : listFiles(dir, true)) { PortalData data = (PortalData) un.unmarshal(file); if (data != null && data.getPortals() != null) newTemplates.addAll(data.getPortals()); } DataManager.PORTAL_DATA.setPortals(newTemplates); } catch (Exception e) { PacketSendUtility.sendMessage(admin, "Portals reload failed!"); log.error(e); } finally { PacketSendUtility.sendMessage(admin, "Portals reloaded successfuly!"); } } else if (params[0].equals("spawn")) { File dir = new File("./data/static_data/spawns"); try { JAXBContext jc = JAXBContext.newInstance(StaticData.class); Unmarshaller un = jc.createUnmarshaller(); un.setSchema(getSchema("./data/static_data/static_data.xsd")); List<SpawnGroup> newTemplates = new ArrayList<SpawnGroup>(); for (File file : listFiles(dir, true)) { SpawnsData data = (SpawnsData) un.unmarshal(file); if (data != null && data.getSpawnGroups() != null) newTemplates.addAll(data.getSpawnGroups()); } DataManager.SPAWNS_DATA.setSpawns(newTemplates); } catch (Exception e) { PacketSendUtility.sendMessage(admin, "Spawns reload failed!"); log.error(e); } finally { PacketSendUtility.sendMessage(admin, "Spawns reloaded successfuly!"); } } else if (params[0].equals("admcmd")) { ChatHandlers.getInstance().reloadChatHandlers(); PacketSendUtility.sendMessage(admin, "Admin commands reloaded successfully!"); } else PacketSendUtility.sendMessage(admin, "syntax //reload <quest | skill | portal | spawn | admcmd>"); }
From source file:com.rest4j.ApiFactory.java
/** * Create the API instance. The XML describing the API is read, preprocessed, analyzed for errors, * and the internal structures for Java object marshalling and unmarshalling are created, as * well as endpoint mappings.//from ww w . jav a2 s .co m * * @return The API instance * @throws ConfigurationException When there is a problem with your XML description. */ public API createAPI() throws ConfigurationException { try { JAXBContext context; if (extObjectFactory == null) context = JAXBContext.newInstance(com.rest4j.impl.model.ObjectFactory.class); else context = JAXBContext.newInstance(com.rest4j.impl.model.ObjectFactory.class, extObjectFactory); Document xml = getDocument(); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Source apiXsdSource = new StreamSource(getClass().getResourceAsStream("api.xsd")); List<Source> xsds = new ArrayList<Source>(); xsds.add(apiXsdSource); Schema schema; if (!StringUtils.isEmpty(extSchema)) { xsds.add(new StreamSource(getClass().getClassLoader().getResourceAsStream(extSchema))); } xsds.add(new StreamSource(getClass().getResourceAsStream("html.xsd"))); schema = schemaFactory.newSchema(xsds.toArray(new Source[xsds.size()])); Unmarshaller unmarshaller = context.createUnmarshaller(); unmarshaller.setSchema(schema); JAXBElement<com.rest4j.impl.model.API> element = (JAXBElement<com.rest4j.impl.model.API>) unmarshaller .unmarshal(xml); com.rest4j.impl.model.API root = element.getValue(); APIImpl api; api = new APIImpl(root, pathPrefix, serviceProvider, factories.toArray(new ObjectFactory[factories.size()]), fieldFilters.toArray(new FieldFilter[fieldFilters.size()]), permissionChecker); return api; } catch (javax.xml.bind.UnmarshalException e) { if (e.getLinkedException() instanceof SAXParseException) { SAXParseException spe = (SAXParseException) e.getLinkedException(); throw new ConfigurationException("Cannot parse " + apiDescriptionXml, spe); } throw new AssertionError(e); } catch (ConfigurationException e) { throw e; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new AssertionError(e); } }
From source file:eu.europa.ejusticeportal.dss.controller.config.Config.java
/** * @param xml/*from www . j a v a 2s. co m*/ * @return * @throws JAXBException */ private JAXBElement<SigningConfigType> parseXml(String xml) throws JAXBException { JAXBContext context; JAXBElement<SigningConfigType> rep; try { context = JAXBContext.newInstance(CardProfileNamespace.NS); Unmarshaller u = context.createUnmarshaller(); u.setSchema(schema); rep = (JAXBElement<SigningConfigType>) u.unmarshal(new StreamSource(new StringReader(xml))); } catch (JAXBException e) { LOGGER.error("XML Error in the dss applet card profile repository file", e); //try again without validation context = JAXBContext.newInstance(CardProfileNamespace.NS); Unmarshaller u = context.createUnmarshaller(); rep = (JAXBElement<SigningConfigType>) u.unmarshal(new StreamSource(new StringReader(xml))); } return rep; }
From source file:main.java.refinement_class.Useful.java
public static Object unmashal(String schema_file, String xml_file, Class c) { Object obj = null;// w ww.ja v a 2 s. c o m try { // create a JAXBContext capable of handling classes generated into // JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class ); JAXBContext jc = JAXBContext.newInstance(c); // create an Unmarshaller Unmarshaller u = jc.createUnmarshaller(); SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); try { // LOG.info("\n\n XX -->> Schema file: " + schema_file); // LOG.info("\n\n XX -->> xml_file file: " + xml_file); //++ javax.xml.validation.Schema schema; if (schema_file.contains("/tmp/")) { schema = sf.newSchema(new File(schema_file)); } else { URL urlSchema = getUrl(H2mserviceImpl.class, schema_file); // LOG.info("\n\n XX -->> urlSchema: " + urlSchema.getPath()); schema = sf.newSchema(urlSchema); } //-- //javax.xml.validation.Schema schema = sf.newSchema(new File(schema_file)); // ++ u.setSchema((javax.xml.validation.Schema) schema); u.setEventHandler(new ValidationEventHandler() { // allow unmarshalling to continue even if there are errors public boolean handleEvent(ValidationEvent ve) { // ignore warnings if (ve.getSeverity() != ValidationEvent.WARNING) { ValidationEventLocator vel = ve.getLocator(); System.out.println("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + "]:" + ve.getMessage()); } return true; } }); } catch (org.xml.sax.SAXException se) { System.out.println("Unable to validate due to following error."); se.printStackTrace(); LOG.error("===>[1]ERROR Unmashaling \n\n" + se.toString()); LOG.error(Useful.getStackTrace(se)); } catch (Exception e) { LOG.error("===>[2]ERROR Unmashaling \n\n" + e.toString()); LOG.error(Useful.getStackTrace(e)); } if (xml_file.contains("/tmp/")) { obj = u.unmarshal(new File(xml_file)); } else { URL url_xml_file = getUrl(H2mserviceImpl.class, xml_file); LOG.info("\n\n XX -->> url_xml_file: " + url_xml_file.getPath()); obj = u.unmarshal(url_xml_file); } //-- //obj = u.unmarshal( new File( xml_file)); //++ // even though document was determined to be invalid unmarshalling, // marshal out result. // System.out.println(""); // System.out.println("Still able to marshal invalid document"); // javax.xml.bind.Marshaller m = jc.createMarshaller(); // m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE ); // m.marshal(poe, System.out); } catch (UnmarshalException ue) { // The JAXB specification does not mandate how the JAXB provider // must behave when attempting to unmarshal invalid XML data. // those cases, the JAXB provider is allowed to terminate the // call to unmarshal with an UnmarshalException. System.out.println("Caught UnmarshalException"); LOG.error("===>[3]ERROR Unmashaling \n\n" + ue.toString()); } catch (JAXBException je) { je.printStackTrace(); LOG.error("===>[4]ERROR Unmashaling \n\n" + je.toString()); LOG.error(Useful.getStackTrace(je)); } catch (Exception e) { LOG.error("===>[5]ERROR Unmashaling \n\n" + e.toString()); LOG.error(Useful.getStackTrace(e)); } if (obj == null) { LOG.error("===>[6]ERROR Unmashaling Object NULL"); } return obj; }
From source file:org.tellervo.desktop.wsi.JaxbResponseHandler.java
public T toDocument(final HttpEntity entity, final String defaultCharset) throws IOException, ParseException { if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); }/*w ww . ja v a2s . com*/ InputStream instream = entity.getContent(); if (instream == null) { return null; } String charset = EntityUtils.getContentCharSet(entity); if (charset == null) { charset = defaultCharset; } if (charset == null) { charset = HTTP.DEFAULT_CONTENT_CHARSET; } /** * Methodology * 1) Save XML to disk temporarily (it can be big, * we might want to look at it as a raw file) * 2) If we can't write to disk, throw IOException * 3) Try to parse * 4) Throw error with the raw document (it's malformed XML) */ File tempFile = null; OutputStreamWriter fileOut = null; boolean usefulFile = false; // preserve this file outside this local context? try { tempFile = File.createTempFile("tellervo", ".xml"); fileOut = new OutputStreamWriter(new FileOutputStream(tempFile, false), charset); // ok, dump the webservice xml to a file BufferedReader webIn = new BufferedReader(new InputStreamReader(instream, charset)); char indata[] = new char[8192]; int inlen; // write the file out while ((inlen = webIn.read(indata)) >= 0) fileOut.write(indata, 0, inlen); fileOut.close(); } catch (IOException ioe) { // File I/O failed (?!) Clean up and re-throw the IOE. if (fileOut != null) fileOut.close(); if (tempFile != null) tempFile.delete(); throw ioe; } try { Unmarshaller um = context.createUnmarshaller(); ValidationEventCollector vec = new ValidationEventCollector(); // validate against this schema um.setSchema(validateSchema); // collect events instead of throwing exceptions um.setEventHandler(vec); // do the magic! Object ret = um.unmarshal(tempFile); // typesafe way of checking if this is the right type! return returnClass.cast(ret); } catch (UnmarshalException ume) { usefulFile = true; throw new ResponseProcessingException(ume, tempFile); } catch (JAXBException jaxbe) { usefulFile = true; throw new ResponseProcessingException(jaxbe, tempFile); } catch (ClassCastException cce) { usefulFile = true; throw new ResponseProcessingException(cce, tempFile); } finally { // clean up and delete if (tempFile != null) { if (!usefulFile) tempFile.delete(); else tempFile.deleteOnExit(); } } /* try { um.un } catch (JDOMException jdome) { // this document must be malformed usefulFile = true; throw new XMLParsingException(jdome, tempFile); } } catch (IOException ioe) { // well, something there failed and it was lower level than just bad XML... if(tempFile != null) { usefulFile = true; throw new XMLParsingException(ioe, tempFile); } throw new XMLParsingException(ioe); } finally { // make sure we closed our file if(fileOut != null) fileOut.close(); // make sure we delete it, too if(tempFile != null) { if (!usefulFile) tempFile.delete(); else tempFile.deleteOnExit(); } } */ }