List of usage examples for javax.xml.bind Unmarshaller unmarshal
public Object unmarshal(javax.xml.stream.XMLEventReader reader) throws JAXBException;
From source file:com.ikon.util.impexp.RepositoryImporter.java
/** * Import documents from filesystem into document repository (recursive). *//*from w ww. j av a 2s . co m*/ private static ImpExpStats importDocumentsHelper(String token, File fs, String fldPath, String metadata, boolean history, boolean uuid, Writer out, InfoDecorator deco) throws FileNotFoundException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException, ExtensionException, AutomationException { log.debug("importDocumentsHelper({}, {}, {}, {}, {}, {}, {}, {})", new Object[] { token, fs, fldPath, metadata, history, uuid, out, deco }); File[] files = fs.listFiles(new RepositoryImporter.NoVersionFilenameFilter()); ImpExpStats stats = new ImpExpStats(); FolderModule fm = ModuleManager.getFolderModule(); MetadataAdapter ma = MetadataAdapter.getInstance(token); ma.setRestoreUuid(uuid); Gson gson = new Gson(); for (int i = 0; i < files.length; i++) { String fileName = files[i].getName(); if (!fileName.endsWith(Config.EXPORT_METADATA_EXT) && !fileName.endsWith(".xml")) { if (files[i].isDirectory()) { Folder fld = new Folder(); boolean api = false; int importedFolder = 0; log.info("Directory: {}", files[i]); try { if (metadata.equals("JSON")) { // Read serialized folder metadata File jsFile = new File(files[i].getPath() + Config.EXPORT_METADATA_EXT); log.info("Folder Metadata: {}", jsFile.getPath()); if (jsFile.exists() && jsFile.canRead()) { FileReader fr = new FileReader(jsFile); FolderMetadata fmd = gson.fromJson(fr, FolderMetadata.class); fr.close(); // Apply metadata fld.setPath(fldPath + "/" + fileName); fmd.setPath(fld.getPath()); ma.importWithMetadata(fmd); if (out != null) { out.write(deco.print(files[i].getPath(), files[i].length(), null)); out.flush(); } } else { log.warn("Unable to read metadata file: {}", jsFile.getPath()); api = true; } } else if (metadata.equals("XML")) { // Read serialized folder metadata File jsFile = new File(files[i].getPath() + ".xml"); log.info("Folder Metadata: {}", jsFile.getPath()); if (jsFile.exists() && jsFile.canRead()) { FileReader fr = new FileReader(jsFile); JAXBContext jaxbContext = JAXBContext.newInstance(FolderMetadata.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); FolderMetadata fmd = (FolderMetadata) jaxbUnmarshaller.unmarshal(fr); fr.close(); // Apply metadata fld.setPath(fldPath + "/" + fileName); fmd.setPath(fld.getPath()); ma.importWithMetadata(fmd); if (out != null) { out.write(deco.print(files[i].getPath(), files[i].length(), null)); out.flush(); } } else { log.warn("Unable to read metadata file: {}", jsFile.getPath()); api = true; } } else { api = true; } if (api) { fld.setPath(fldPath + "/" + fileName); fm.create(token, fld); FileLogger.info(BASE_NAME, "Created folder ''{0}''", fld.getPath()); if (out != null) { out.write(deco.print(files[i].getPath(), files[i].length(), null)); out.flush(); } } importedFolder = 1; } catch (ItemExistsException e) { log.warn("ItemExistsException: {}", e.getMessage()); if (out != null) { out.write(deco.print(files[i].getPath(), files[i].length(), "ItemExists")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "ItemExistsException ''{0}''", fld.getPath()); } catch (JsonParseException e) { log.warn("JsonParseException: {}", e.getMessage()); if (out != null) { out.write(deco.print(files[i].getPath(), files[i].length(), "Json")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "JsonParseException ''{0}''", fld.getPath()); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } ImpExpStats tmp = importDocumentsHelper(token, files[i], fld.getPath(), metadata, history, uuid, out, deco); // Stats stats.setOk(stats.isOk() && tmp.isOk()); stats.setSize(stats.getSize() + tmp.getSize()); stats.setMails(stats.getMails() + tmp.getMails()); stats.setDocuments(stats.getDocuments() + tmp.getDocuments()); stats.setFolders(stats.getFolders() + tmp.getFolders() + importedFolder); } else { log.info("File: {}", files[i]); if (fileName.endsWith(".eml")) { log.info("Mail: {}", files[i]); ImpExpStats tmp = importMail(token, fs, fldPath, fileName, files[i], metadata, out, deco); // Stats stats.setOk(stats.isOk() && tmp.isOk()); stats.setSize(stats.getSize() + tmp.getSize()); stats.setMails(stats.getMails() + tmp.getMails()); } else { log.info("Document: {}", files[i]); ImpExpStats tmp = importDocument(token, fs, fldPath, fileName, files[i], metadata, history, out, deco); // Stats stats.setOk(stats.isOk() && tmp.isOk()); stats.setSize(stats.getSize() + tmp.getSize()); stats.setDocuments(stats.getDocuments() + tmp.getDocuments()); } } } } log.debug("importDocumentsHelper: {}", stats); return stats; }
From source file:Main.java
/** * Unmarshal XML data from XML file path using XSD string and return the resulting JAXB content tree * /*from w ww. j av a2 s . c o m*/ * @param dummyCtxObject * Dummy contect object for creating related JAXB context * @param strXMLFilePath * XML file path * @param strXSD * XSD * @return resulting JAXB content tree * @throws Exception * in error case */ public static Object doUnmarshallingFromXMLFile(Object dummyCtxObject, String strXMLFilePath, String strXSD) throws Exception { if (dummyCtxObject == null) { throw new RuntimeException("No dummy context object (null)!"); } if (strXMLFilePath == null) { throw new RuntimeException("No XML file path (null)!"); } if (strXSD == null) { throw new RuntimeException("No XSD (null)!"); } Object unmarshalledObject = null; try { JAXBContext jaxbCtx = JAXBContext.newInstance(dummyCtxObject.getClass().getPackage().getName()); Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller(); // unmarshaller.setValidating(true); /* javax.xml.validation.Schema schema = javax.xml.validation.SchemaFactory.newInstance( javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema( new java.io.File(m_strXSDFilePath)); */ StringReader reader = null; FileInputStream fis = null; try { reader = new StringReader(strXSD); javax.xml.validation.Schema schema = javax.xml.validation.SchemaFactory .newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI) .newSchema(new StreamSource(reader)); unmarshaller.setSchema(schema); fis = new FileInputStream(strXMLFilePath); unmarshalledObject = unmarshaller.unmarshal(fis); } finally { if (fis != null) { fis.close(); fis = null; } if (reader != null) { reader.close(); reader = null; } } // } catch (JAXBException e) { // //m_logger.error(e); // throw new OrderException(e); } catch (Exception e) { // Logger.XMLEval.logState("Unmarshalling failed: " + e.getMessage(), LogLevel.Error); throw e; } return unmarshalledObject; }
From source file:gov.nih.nci.ncicb.tcga.dcc.common.jaxb.JAXBUtil.java
/** * This method unmarshals an XML file into a JAXB object element. * <p/>/* w w w .j a v a2 s .c o m*/ * <p/> * The underlying type of the JAXB object element returned by this method will correspond * to the JAXB object(s) referenced by the package namespace provided in the parameter list. * <p/> * <p/> * If the <code>filterMetaDataNamespaces</code> parameter is set to true, this method will use * the {@link MetaDataXMLNamespaceFilter} to filter the namespace URI of specific meta-data * elements during unmarshalling that correspond to the TCGA_BCR.Metadata XSD. * <p/> * <p/> * If the <code>validate</code> parameter is set to true, schema validation will be performed. * <p/> * <p/> * If both <code>filterMetaDataNamespaces</code> and <code>validate</code> are set to true, * only the meta-data elements will go through schema validation. * * @param xmlFile - a {@link File} object representing the XML file to unmarshalled * @param jaxbPackageName - a string that represents package namespace of the JAXB context objects * @param filterMetaDataNamespaces - boolean that specifies whether or not to filter meta-data * namespace URIs using the {@link MetaDataXMLNamespaceFilter} * @param validate - boolean indicating weather or not the XML should be validated against a schema * @return - an instance of {@link UnmarshalResult} representing the result of the unmarhsalling * @throws UnmarshalException if an error occurs during unmarshalling */ public static UnmarshalResult unmarshal(final File xmlFile, final String jaxbPackageName, final boolean filterMetaDataNamespaces, final boolean validate) throws UnmarshalException { Object jaxbObject = null; ValidationEventCollector validationEventCollector = (validate ? new ValidationEventCollector() : null); JAXBContext jaxbContext; Unmarshaller unmarshaller; if (xmlFile != null && jaxbPackageName != null) { FileReader xmlFileReader = null; try { // Get the JAXB context using the package name and create an unmarshaller jaxbContext = JAXBContext.newInstance(jaxbPackageName); unmarshaller = jaxbContext.createUnmarshaller(); xmlFileReader = new FileReader(xmlFile); // Unmarshal the XML file if (filterMetaDataNamespaces) { final SAXSource source = applyMetaDataNamespaceFilter(unmarshaller, xmlFileReader); jaxbObject = unmarshaller.unmarshal(source); // Perform schema validation meta-data elements only if (validate) { final String metaDataXML = getMetaDataXMLAsString(jaxbContext, jaxbObject); jaxbObject = validate(unmarshaller, validationEventCollector, new StringReader(metaDataXML), true); } } else { // Perform schema validation of all XML elements if (validate) { jaxbObject = validate(unmarshaller, validationEventCollector, xmlFileReader, false); } else { jaxbObject = unmarshaller.unmarshal(xmlFile); } } } catch (Exception e) { throw new UnmarshalException(e); } finally { IOUtils.closeQuietly(xmlFileReader); } } else { throw new UnmarshalException(new StringBuilder() .append("Unmarshalling failed because either the XML file '").append(xmlFile) .append("' or package namespace '").append(jaxbPackageName).append("' was null").toString()); } // Return the result of the unmarshalling if (validationEventCollector != null) { return new UnmarshalResult(jaxbObject, Arrays.asList(validationEventCollector.getEvents())); } else { return new UnmarshalResult(jaxbObject, new ArrayList<ValidationEvent>()); } }
From source file:com.jsmartframework.web.manager.WebContext.java
/** * Get request content from XML and convert it to class mapping the content. * * @param unmarshaller - JAXBContext unmarshaller to convert the request content into object. * @param <T> - type of class to convert XML into class. * * @return content from XML to object/*w w w. ja v a 2 s .c o m*/ * @throws IOException */ public static <T> T getContentFromXml(Unmarshaller unmarshaller) throws IOException, JAXBException { StringReader reader = new StringReader(getContentAsString()); return (T) unmarshaller.unmarshal(reader); }
From source file:com.ikon.util.impexp.RepositoryImporter.java
/** * Import document./*from ww w . ja v a 2 s . co m*/ */ private static ImpExpStats importDocument(String token, File fs, String fldPath, String fileName, File fDoc, String metadata, boolean history, Writer out, InfoDecorator deco) throws IOException, RepositoryException, DatabaseException, PathNotFoundException, AccessDeniedException, ExtensionException, AutomationException { FileInputStream fisContent = new FileInputStream(fDoc); MetadataAdapter ma = MetadataAdapter.getInstance(token); DocumentModule dm = ModuleManager.getDocumentModule(); ImpExpStats stats = new ImpExpStats(); int size = fisContent.available(); Document doc = new Document(); Gson gson = new Gson(); boolean api = false; try { // Metadata if (!metadata.equals("none")) { boolean isJsonFile = metadata.equals("JSON"); // Read serialized document metadata File jsFile = null; if (isJsonFile) jsFile = new File(fDoc.getPath() + Config.EXPORT_METADATA_EXT); else jsFile = new File(fDoc.getPath() + ".xml"); log.info("Document Metadata File: {}", jsFile.getPath()); if (jsFile.exists() && jsFile.canRead()) { FileReader fr = new FileReader(jsFile); DocumentMetadata dmd = null; //for json file metadata if (isJsonFile) dmd = gson.fromJson(fr, DocumentMetadata.class); else { JAXBContext jaxbContext = JAXBContext.newInstance(DocumentMetadata.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); dmd = (DocumentMetadata) jaxbUnmarshaller.unmarshal(fr); } doc.setPath(fldPath + "/" + fileName); dmd.setPath(doc.getPath()); IOUtils.closeQuietly(fr); log.info("Document Metadata: {}", dmd); if (history && containsHistoryFiles(fs, fileName)) { File[] vhFiles = fs.listFiles(new RepositoryImporter.VersionFilenameFilter(fileName)); List<File> listFiles = Arrays.asList(vhFiles); Collections.sort(listFiles, FilenameVersionComparator.getInstance()); boolean first = true; for (File vhf : vhFiles) { String vhfName = vhf.getName(); int idx = vhfName.lastIndexOf('#', vhfName.length() - 2); String verName = vhfName.substring(idx + 2, vhfName.length() - 1); FileInputStream fis = new FileInputStream(vhf); File jsVerFile = new File(vhf.getPath() + Config.EXPORT_METADATA_EXT); log.info("Document Version Metadata File: {}", jsVerFile.getPath()); if (jsVerFile.exists() && jsVerFile.canRead()) { FileReader verFr = new FileReader(jsVerFile); VersionMetadata vmd = gson.fromJson(verFr, VersionMetadata.class); IOUtils.closeQuietly(verFr); if (first) { dmd.setVersion(vmd); size = fis.available(); ma.importWithMetadata(dmd, fis); first = false; } else { log.info("Document Version Metadata: {}", vmd); size = fis.available(); ma.importWithMetadata(doc.getPath(), vmd, fis); } } else { log.warn("Unable to read metadata file: {}", jsVerFile.getPath()); } IOUtils.closeQuietly(fis); FileLogger.info(BASE_NAME, "Created document ''{0}'' version ''{1}''", doc.getPath(), verName); log.info("Created document '{}' version '{}'", doc.getPath(), verName); } } else { // Apply metadata ma.importWithMetadata(dmd, fisContent); FileLogger.info(BASE_NAME, "Created document ''{0}''", doc.getPath()); log.info("Created document '{}'", doc.getPath()); } } else { log.warn("Unable to read metadata file: {}", jsFile.getPath()); api = true; } } else { api = true; } if (api) { doc.setPath(fldPath + "/" + fileName); // Version history if (history) { File[] vhFiles = fs.listFiles(new RepositoryImporter.VersionFilenameFilter(fileName)); List<File> listFiles = Arrays.asList(vhFiles); Collections.sort(listFiles, FilenameVersionComparator.getInstance()); boolean first = true; for (File vhf : vhFiles) { String vhfName = vhf.getName(); int idx = vhfName.lastIndexOf('#', vhfName.length() - 2); String verName = vhfName.substring(idx + 2, vhfName.length() - 1); FileInputStream fis = new FileInputStream(vhf); if (first) { dm.create(token, doc, fis); first = false; } else { dm.checkout(token, doc.getPath()); dm.checkin(token, doc.getPath(), fis, "Imported from administration"); } IOUtils.closeQuietly(fis); FileLogger.info(BASE_NAME, "Created document ''{0}'' version ''{1}''", doc.getPath(), verName); log.info("Created document '{}' version '{}'", doc.getPath(), verName); } } else { dm.create(token, doc, fisContent); FileLogger.info(BASE_NAME, "Created document ''{0}''", doc.getPath()); log.info("Created document ''{}''", doc.getPath()); } } if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), null)); out.flush(); } // Stats stats.setSize(stats.getSize() + size); stats.setDocuments(stats.getDocuments() + 1); } catch (UnsupportedMimeTypeException e) { log.warn("UnsupportedMimeTypeException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "UnsupportedMimeType")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "UnsupportedMimeTypeException ''{0}''", doc.getPath()); } catch (FileSizeExceededException e) { log.warn("FileSizeExceededException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "FileSizeExceeded")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "FileSizeExceededException ''{0}''", doc.getPath()); } catch (UserQuotaExceededException e) { log.warn("UserQuotaExceededException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "UserQuotaExceeded")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "UserQuotaExceededException ''{0}''", doc.getPath()); } catch (VirusDetectedException e) { log.warn("VirusWarningException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "VirusWarningException")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "VirusWarningException ''{0}''", doc.getPath()); } catch (ItemExistsException e) { log.warn("ItemExistsException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "ItemExists")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "ItemExistsException ''{0}''", doc.getPath()); } catch (LockException e) { log.warn("LockException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "Lock")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "LockException ''{0}''", doc.getPath()); } catch (VersionException e) { log.warn("VersionException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "Version")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "VersionException ''{0}''", doc.getPath()); } catch (JsonParseException e) { log.warn("JsonParseException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "Json")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "JsonParseException ''{0}''", doc.getPath()); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { IOUtils.closeQuietly(fisContent); } return stats; }
From source file:gov.nih.nci.ncicb.tcga.dcc.common.jaxb.JAXBUtil.java
private static Object validate(final Unmarshaller unmarshaller, final ValidationEventHandler validationEventHandler, final Reader reader, final boolean includeMetaDataSchema) throws JAXBException, SAXException, IOException { Object jaxbObject = null;/*from ww w .j a va2 s . c o m*/ try { // Set the schema for the unmarshaller final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); final Schema schema = schemaFactory .newSchema(getSchemaSources(includeMetaDataSchema).toArray(new Source[] {})); unmarshaller.setSchema(schema); unmarshaller.setEventHandler(validationEventHandler); // Unmarshal and validate jaxbObject = unmarshaller.unmarshal(reader); } catch (UnmarshalException ue) { // Swallow the exception. The ValidationEventHandler attached to the unmarshaller will // contain the validation events logger.info(ue); } return jaxbObject; }
From source file:StringAdapter.java
private void demo(String xml) throws JAXBException { StringReader stringReader = new StringReader(xml); Unmarshaller unmarshaller = jc.createUnmarshaller(); Root root = (Root) unmarshaller.unmarshal(stringReader); System.out.println("ITEM: " + root.getItem()); System.out.print("OUTPUT: "); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); marshaller.marshal(root, System.out); }
From source file:com.mycompany.dao.report.XMLReport.java
@Override public void generate() throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(Books.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Books books = (Books) jaxbUnmarshaller.unmarshal(new File(fileName)); for (Iterator<Book> iterator = books.getBooks().iterator(); iterator.hasNext();) { Book book = iterator.next(); if (book.getQuantity() != 0) { // Remove the current element from the iterator and the list. iterator.remove();// w ww . j av a2s. co m } } Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(books, new File(fileName2)); }
From source file:org.jasig.portlet.campuslife.dao.MockDataService.java
@Override public void afterPropertiesSet() throws Exception { try {//w w w . j av a 2 s. c o m JAXBContext jaxbContext = JAXBContext.newInstance(getPackageName()); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); this.data = (T) unmarshaller.unmarshal(feed.getInputStream()); } catch (IOException e) { log.error("Failed to read mock data", e); } catch (JAXBException e) { log.error("Failed to unmarshall mock data", e); } }
From source file:com.wso2telco.core.mnc.resolver.ConfigLoader.java
/** * Inits the mcc config.//from ww w .j a v a2 s . c om * * @return the MCC configuration * @throws JAXBException the JAXB exception */ private MCCConfiguration initMccConfig() throws JAXBException { String configPath = CarbonUtils.getCarbonConfigDirPath() + File.separator + "MobileCountryConfig.xml"; File file = new File(configPath); JAXBContext ctx = JAXBContext.newInstance(MCCConfiguration.class); Unmarshaller um = ctx.createUnmarshaller(); return (MCCConfiguration) um.unmarshal(file); }