Example usage for javax.xml.bind Unmarshaller unmarshal

List of usage examples for javax.xml.bind Unmarshaller unmarshal

Introduction

In this page you can find the example usage for javax.xml.bind Unmarshaller unmarshal.

Prototype

public Object unmarshal(javax.xml.stream.XMLEventReader reader) throws JAXBException;

Source Link

Document

Unmarshal XML data from the specified pull parser and return the resulting content tree.

Usage

From source file:hydrograph.ui.dataviewer.utilities.ViewDataSchemaHelper.java

/**
 * This function will read schema file and return schema fields
 * @param schemaFilePath/*from w  w  w .j a  v  a 2 s.  co  m*/
 * @return Fields
 */
public Fields getFieldsFromSchema(String schemaFilePath) {
    Fields fields = null;
    if (StringUtils.isNotBlank(schemaFilePath)) {
        String filePath = ((IPath) new Path(schemaFilePath)).removeFileExtension()
                .addFileExtension(Constants.XML_EXTENSION_FOR_IPATH).toString();
        File file = new File(filePath);
        if (file.exists()) {
            try {
                DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
                builderFactory.setExpandEntityReferences(false);
                builderFactory.setNamespaceAware(true);
                builderFactory.setFeature(Constants.DISALLOW_DOCTYPE_DECLARATION, true);

                DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();

                Document document = documentBuilder.parse(file);
                JAXBContext jaxbContext = JAXBContext.newInstance(Schema.class);
                Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                Schema schema = (Schema) jaxbUnmarshaller.unmarshal(document);
                fields = schema.getFields();
                for (Field field : fields.getField()) {
                    logger.debug("Type:{}, Name:{}, Format:{}" + field.getType(), field.getName(),
                            field.getFormat());
                }
            } catch (JAXBException | ParserConfigurationException | SAXException | IOException exception) {
                logger.error("Invalid xml file: ", exception);
            }
        }
    }
    return fields;
}

From source file:org.apache.cxf.systest.jaxrs.JAXRSClientServerStreamingTest.java

private Book readBook(InputStream is) throws Exception {
    JAXBContext c = JAXBContext.newInstance(new Class[] { Book.class });
    Unmarshaller u = c.createUnmarshaller();
    return (Book) u.unmarshal(is);
}

From source file:com.iata.ndc.trial.controllers.DefaultController.java

@RequestMapping(method = RequestMethod.GET)
public String index(ModelMap map) throws JAXBException, ClientProtocolException, ClientException, IOException {

    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource("AirShopping.xml").getFile());
    JAXBContext jaxbContext = JAXBContext.newInstance(AirShoppingRQ.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    AirShoppingRQ request = (AirShoppingRQ) jaxbUnmarshaller.unmarshal(file);
    NdcClient client = new NdcClient("http://iata.api.mashery.com/athena/api", "jhttds6eh5bgq92zvqnruehx");
    List<FlightConnection> response = new AirShoppingResonseMapper()
            .mapAirShoppingResponse(client.airShopping(request));

    return "index";
}

From source file:com.healthcit.cacure.web.controller.FormExportController.java

@RequestMapping(method = RequestMethod.POST)
public ModelAndView importForm(@RequestParam("file") MultipartFile file,
        @RequestParam("moduleId") long moduleId, HttpServletRequest request, HttpServletResponse response) {
    try {//from www .ja  va  2s .  c o m
        if (file != null) {
            Map<String, String> existingForms = new HashMap<String, String>();
            List<String> existingQuestions = new ArrayList<String>();
            InputStream is = file.getInputStream();
            JAXBContext jc = JAXBContext.newInstance("com.healthcit.cacure.export.model");
            Unmarshaller m = jc.createUnmarshaller();
            Cure cure = (Cure) m.unmarshal(is);
            dataImporter.importData(cure, moduleId, existingForms, existingQuestions);
            if (existingForms.size() > 0 || existingQuestions.size() > 0) {
                ModelAndView mav = new ModelAndView("formUploadStatus"); // initialize with view name
                ModelMap model = mav.getModelMap();
                model.addAttribute("existingForms", existingForms);
                model.addAttribute("existingQuestions", existingQuestions);
                return mav;
                /* there had been errors */
                //               return new ModelAndView("formUploadStatus", "existingForms", existingForms);
            }
        }
        return new ModelAndView("formUploadStatus", "status", "OK");

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return new ModelAndView("formUploadStatus", "status", "FAIL");
    }
}

From source file:org.openmrs.module.dhisreport.api.model.ReportTemplatesTest.java

@Test
public void unMarshallReportTemplates() throws Exception {
    ClassPathResource resource = new ClassPathResource("templates_ethiopia.xml");
    JAXBContext jaxbContext = JAXBContext.newInstance(ReportTemplates.class);

    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    ReportTemplates reportTemplates = (ReportTemplates) jaxbUnmarshaller.unmarshal(resource.getInputStream());
    assertNotNull(reportTemplates);/*  w  w  w.  j a  va  2  s. com*/
    List<ReportDefinition> reportDefinitions = reportTemplates.getReportDefinitions();
    assertEquals(2, reportDefinitions.size());
    for (ReportDefinition rd : reportDefinitions) {
        for (DataValueTemplate dvt : rd.getDataValueTemplates()) {
            assertNotNull(dvt.getDataelement());
            assertNotNull(dvt.getDataelement().getCode());
            assertNotNull(dvt.getDataelement().getName());
            assertNotNull(dvt.getDataelement().getUid());
            assertNotNull(dvt.getDisaggregation());
            assertNotNull(dvt.getDisaggregation().getCode());
            assertNotNull(dvt.getDisaggregation().getName());
            assertNotNull(dvt.getDisaggregation().getUid());
        }
    }
}

From source file:be.fedict.trust.tsl.TSLParser.java

private TrustStatusListType parseTslInputStream() throws JAXBException {
    Unmarshaller unmarshaller = getUnmarshaller();
    JAXBElement<TrustStatusListType> jaxbElement = (JAXBElement<TrustStatusListType>) unmarshaller
            .unmarshal(this.tslInputStream);
    TrustStatusListType trustServiceStatusList = jaxbElement.getValue();
    return trustServiceStatusList;
}

From source file:com.castlemock.web.basis.support.FileRepositorySupport.java

public <T> Collection<T> load(Class<T> entityClass, String directory, String postfix) {
    final Collection<T> loadedTypes = new ArrayList<T>();
    final Path path = FileSystems.getDefault().getPath(directory);
    if (!Files.exists(path)) {
        try {/*w  w  w. j  a  va  2  s  .  c o m*/
            LOGGER.debug("Creating the following directory: " + path);
            Files.createDirectories(path);
        } catch (IOException e) {
            LOGGER.error("Unable to create the following directory: " + path, e);
            throw new IllegalStateException("Unable to create the following folder: " + directory);
        }
    }
    if (!Files.isDirectory(path)) {
        throw new IllegalStateException("The provided path is not a directory: " + path);
    }

    final File folder = new File(directory);
    try {
        LOGGER.debug("Start loading files for the following type: " + entityClass.getSimpleName());
        for (final File file : folder.listFiles()) {
            if (file.isFile() && file.getName().endsWith(postfix)) {
                JAXBContext jaxbContext = JAXBContext.newInstance(entityClass);
                Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                T type = (T) jaxbUnmarshaller.unmarshal(file);
                loadedTypes.add(type);
                LOGGER.debug("\tLoaded " + file.getName());
            }
        }
    } catch (JAXBException e) {
        LOGGER.error("Unable to parse files for type " + entityClass.getSimpleName(), e);
    }
    return loadedTypes;
}

From source file:com.healthcit.cacure.web.controller.ModuleImportExportController.java

@RequestMapping(method = RequestMethod.POST)
public ModelAndView importModule(@RequestParam("file") MultipartFile file, HttpServletRequest request,
        HttpServletResponse response) {//from ww w .ja v  a2s  .  co  m
    try {
        if (file != null) {
            Map<String, String> existingForms = new HashMap<String, String>();
            Map<String, String> existingModules = new HashMap<String, String>();
            List<String> existingQuestions = new ArrayList<String>();

            InputStream is = file.getInputStream();
            JAXBContext jc = JAXBContext.newInstance("com.healthcit.cacure.export.model");
            Unmarshaller m = jc.createUnmarshaller();
            Cure cure = (Cure) m.unmarshal(is);
            dataImporter.importModule(cure, existingModules, existingForms, existingQuestions);
            if (existingModules.size() > 0 || existingForms.size() > 0 || existingQuestions.size() > 0) {
                ModelAndView mav = new ModelAndView("formUploadStatus"); // initialize with view name
                ModelMap model = mav.getModelMap();
                model.addAttribute("existingModules", existingModules);
                model.addAttribute("existingForms", existingForms);
                model.addAttribute("existingQuestions", existingQuestions);
                return mav;
                /* there had been errors */
                //               return new ModelAndView("formUploadStatus", "existingForms", existingForms);
            }
        }
        return new ModelAndView("formUploadStatus", "status", "OK");

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return new ModelAndView("formUploadStatus", "status", "FAIL");
    }

}

From source file:com.spend.spendService.SearchText.java

private SearchEngines getSearchEnginesFromXml() {
    try {/*  ww  w. j a v a 2s  .  co m*/
        File file = new File("SearchEngines.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(SearchEngines.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        SearchEngines searchEngineList = (SearchEngines) jaxbUnmarshaller.unmarshal(file);
        return searchEngineList;
    } catch (JAXBException ex) {
        System.out.println("SearchText.java getSearchEnginesFromXml function ERROR " + ex.getMessage());
        ex.printStackTrace();
    }
    return null;
}

From source file:ch.windmobile.server.file.FileDataSource.java

@Override
public Chart getWindChart(String stationId, int duration) throws DataSourceException {
    try {/*from   ww w .  j  a va 2  s .  com*/
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        Chart windChart = (Chart) unmarshaller.unmarshal(getWindChartResource().getInputStream());
        return windChart;
    } catch (Exception e) {
        throw new DataSourceException(DataSourceException.Error.INVALID_DATA, "Unable to parse the test data",
                e);
    }
}