Example usage for javax.xml.bind JAXBContext createUnmarshaller

List of usage examples for javax.xml.bind JAXBContext createUnmarshaller

Introduction

In this page you can find the example usage for javax.xml.bind JAXBContext createUnmarshaller.

Prototype

public abstract Unmarshaller createUnmarshaller() throws JAXBException;

Source Link

Document

Create an Unmarshaller object that can be used to convert XML data into a java content tree.

Usage

From source file:edu.cornell.med.icb.goby.modes.StatsMode.java

private void loadInfo() {
    try {//from  w w  w  .  j a v  a  2s .  c o m
        final JAXBContext jc = JAXBContext.newInstance(InfoOutput.class);

        final Unmarshaller m = jc.createUnmarshaller();
        InfoOutput info = (InfoOutput) m.unmarshal(new File(infoFilename));
        for (AnnotationLength ae : info.lengths) {
            int index = deCalculator.getElementIndex(ae.id);
            if (index != -1) {

                deCalculator.defineElementLength(index, ae.length);
            } else {

                // OK since some elements will yield zero counts and not be in the input.
            }
        }
        for (SampleTotalCount tc : info.totalCounts) {
            deCalculator.setNumAlignedInSample(tc.sampleId, tc.totalCount);
        }
    } catch (JAXBException e) {
        System.err.printf("An error occurred loading the content of info file %s %n", infoFilename);
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:org.javelin.sws.ext.bind.SweJaxbUnmarshallerTest.java

@Test(expected = UnmarshalException.class)
public void unmarshalVeryComplexContent() throws Exception {
    JAXBContext context = JAXBContext.newInstance("org.javelin.sws.ext.bind.context1");
    // ClassWithVeryComplexContent value = new ClassWithVeryComplexContent("test", "str", new ClassWithComplexContent("test", 42, "inside"));
    Unmarshaller um = context.createUnmarshaller();
    InputStream inputStream = new ClassPathResource("very-complex-content-01.xml", this.getClass())
            .getInputStream();//  w  ww  .  ja  v  a  2 s  .  c  om
    um.unmarshal(XMLInputFactory.newFactory().createXMLEventReader(inputStream));
}

From source file:org.jasig.portlet.maps.dao.GoogleMyMapsDaoImpl.java

@Override
@Cacheable("mapCache")
public MapData getMap(String selectedMapDataUrl) {

    //todo change this method to use the string passed in

    final MapData map = new MapData();

    // read a Google My Maps KML feed from the local filesystem and parse 
    // it using JAXB
    Kml kml = null;/*w w w  .  j  av a 2s . c o  m*/
    try {
        JAXBContext jc = JAXBContext.newInstance(Kml.class);
        Unmarshaller u = jc.createUnmarshaller();
        kml = (Kml) u.unmarshal(kmlFile.getInputStream());
    } catch (JAXBException e) {
        log.error("Failed to parse KML file", e);
    } catch (FileNotFoundException e) {
        log.error("Failed to locate KML file", e);
    } catch (IOException e) {
        log.error("IO Exception reading KML file", e);
    }

    final Document doc = (Document) kml.getDocument();

    // iterate through the list of styles building up a map of style IDs
    // to category names
    final Map<String, String> styles = new HashMap<String, String>();
    for (Style style : doc.getStyle()) {
        if (!styles.containsKey(style.getId())) {
            final String iconUrl = style.getIconStyle().getIcon().getHref();
            if (categories.containsKey(iconUrl)) {
                styles.put("#".concat(style.getId()), categories.get(iconUrl));
            }
        }
    }

    final AntiSamy as = new AntiSamy();

    // iterate through the list of placemarks, constructing a location for
    // each item
    int index = 0;
    for (final Placemark placemark : doc.getPlacemark()) {

        // create a new location, setting the name and description
        final Location location = new Location();
        location.setName(placemark.getName());

        try {
            final CleanResults cr = as.scan(placemark.getDescription(), policy);
            location.setDescription(cr.getCleanHTML());
        } catch (ScanException e) {
            log.warn("Exception scanning description", e);
        } catch (PolicyException e) {
            log.warn("Exception cleaning description", e);
        }

        if (this.addresses != null && this.addresses.containsKey(placemark.getName())) {
            location.setAddress(this.addresses.get(placemark.getName()));
        }

        // set the coordinates for the location
        final String[] coordinates = placemark.getPoint().getCoordinates().split(",");
        location.setLatitude(new BigDecimal(Double.parseDouble(coordinates[1])));
        location.setLongitude(new BigDecimal(Double.parseDouble(coordinates[0])));

        // set the abbreviation to the index number just so we have a 
        // unique ID
        location.setAbbreviation(String.valueOf(index));
        index++;

        // if the style ID is mapped to a map category, add the category
        // to this location
        if (styles.containsKey(placemark.getStyleUrl())) {
            location.getCategories().add(styles.get(placemark.getStyleUrl()));
        }

        map.getLocations().add(location);

    }

    postProcessData(map);
    return map;
}

From source file:com.u2apple.tool.dao.DeviceXmlDaoJaxbImpl.java

/**
 * ?.//w  w w  .j a  va  2s .  c o  m
 *
 * @return
 * @throws ShuameException
 */
private void loadStaticMapFile() throws JAXBException {
    File file = new File(Configuration.getProperty(Constants.DEVICES_XML));
    JAXBContext jaxbContext = JAXBContext.newInstance(StaticMapFile.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    staticMapFile = (StaticMapFile) jaxbUnmarshaller.unmarshal(file);
}

From source file:org.javelin.sws.ext.bind.SweJaxbUnmarshallerTest.java

/**
 * RI can unmarshal only to {@link XmlRootElement} annotated classes or to classes passed as a second argument to {@link Unmarshaller#unmarshal(javax.xml.stream.XMLEventReader, Class)}
 * /*w w  w  . j a  v a 2 s .  co  m*/
 * @throws Exception
 */
@Test(expected = UnmarshalException.class)
public void unmarshalVeryComplexContentRI() throws Exception {
    JAXBContext context = ContextFactory.createContext(new Class[] {
            org.javelin.sws.ext.bind.jaxb.context6.ClassWithVeryComplexContent.class, SingleRootElement.class },
            new HashMap<String, Object>());
    Unmarshaller um = context.createUnmarshaller();
    InputStream inputStream = new ClassPathResource("very-complex-content-01.xml", this.getClass())
            .getInputStream();
    // will throw javax.xml.bind.UnmarshalException: unexpected element (uri:"urn:test", local:"root"). Expected elements are <{y}x"
    um.unmarshal(XMLInputFactory.newFactory().createXMLEventReader(inputStream));
}

From source file:com.wso2telco.PremiumInfoScopeTest.java

/**
 * Read scopes config.//www  . j  a  va  2  s. c o m
 *
 * @return the scope configs
 * @throws JAXBException the JAXB exception
 */
private ScopeConfigs readScopesConfig() throws JAXBException {
    Unmarshaller um = null;
    ScopeConfigs userClaims = null;
    String configPath = "config" + File.separator + "scope-config.xml";
    File file = new File(getClass().getClassLoader().getResource(configPath).getFile());
    try {
        JAXBContext ctx = JAXBContext.newInstance(ScopeConfigs.class);
        um = ctx.createUnmarshaller();
        userClaims = (ScopeConfigs) um.unmarshal(file);
    } catch (JAXBException e) {
        throw new JAXBException("Error unmarshalling file :" + configPath);
    }
    return userClaims;
}

From source file:be.e_contract.mycarenet.certra.CertRAClient.java

public EHActorQualitiesDataResponse getActorQualities(byte[] signedCms) throws Exception {
    GetEHActorQualitiesRequest request = this.protocolObjectFactory.createGetEHActorQualitiesRequest();
    request.setEHActorQualitiesDataRequest(signedCms);

    GetEHActorQualitiesResponse response = this.port.getActorQualities(request);
    byte[] responseCms = response.getEHActorQualitiesDataResponse();

    byte[] responseData = getCmsData(responseCms);

    JAXBContext jaxbContext = JAXBContext
            .newInstance(be.e_contract.mycarenet.certra.cms.aqdr.ObjectFactory.class);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    EHActorQualitiesDataResponse ehActorQualitiesDataResponse = (EHActorQualitiesDataResponse) unmarshaller
            .unmarshal(new ByteArrayInputStream(responseData));
    return ehActorQualitiesDataResponse;
}

From source file:com.azaptree.services.spring.application.config.SpringApplicationServiceConfig.java

private SpringApplicationService parse(final InputStream xml) throws JAXBException {
    Assert.notNull(xml);// ww w.j a  v a2  s  .c o m
    final JAXBContext jc = JAXBContext.newInstance(SpringApplicationService.class);
    final Unmarshaller u = jc.createUnmarshaller();
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final ByteArrayOutputStream bos = new ByteArrayOutputStream(512);
    generateSchema(bos);
    try {
        final SpringApplicationService springApplicationService = (SpringApplicationService) u.unmarshal(xml);
        final Schema schema = schemaFactory
                .newSchema(new StreamSource(new ByteArrayInputStream(bos.toByteArray())));
        final Validator validator = schema.newValidator();
        validator.validate(new JAXBSource(jc, springApplicationService));
        return springApplicationService;
    } catch (SAXException | IOException e) {
        throw new IllegalArgumentException(
                "Failed to parse XML. The XML must conform to the following schema:\n" + bos, e);
    }
}

From source file:fr.cls.atoll.motu.api.rest.MotuRequest.java

/**
 * Gets the message as XML.//w  w  w.j  ava  2 s  . c o  m
 * 
 * @param in the in
 * 
 * @return the message as XML
 * 
 * @throws MotuRequestException the motu request exception
 */
public static Object getMessageAsXML(InputStream in) throws MotuRequestException {

    Object object = null;

    try {
        JAXBContext jc = JAXBContext.newInstance(MotuMsgConstant.MOTU_MSG_SCHEMA_PACK_NAME);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        object = unmarshaller.unmarshal(in);
    } catch (Exception e) {
        throw new MotuRequestException("request reading error in getMessageAsXML", e);
    }

    if (object == null) {
        throw new MotuRequestException("Unable to load XML in getMessageAsXML (returned object is null)");
    }
    try {
        in.close();
    } catch (IOException io) {
        // Do nothing
    }

    return object;
}