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:it.polimi.modaclouds.qos_models.util.XMLHelper.java

public static <T> ValidationResult validate(URL xmlUrl, Class<T> targetClass) {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Unmarshaller unmarshaller;
    ValidationResult result;//w w  w. j a  va2 s.  co m
    try {
        Schema schema = schemaFactory.newSchema();
        unmarshaller = JAXBContext.newInstance(targetClass).createUnmarshaller();
        unmarshaller.setSchema(schema);
    } catch (SAXException | JAXBException e) {
        result = new ValidationResult(false);
        result.addMessage("Error occured in creating the schema");
        result.addMessage(e.getLocalizedMessage());
        return result;
    }
    try {
        unmarshaller.unmarshal(xmlUrl);
    } catch (JAXBException e) {
        result = new ValidationResult(false);
        if (e.getMessage() != null)
            result.addMessage(e.getLocalizedMessage());
        if (e.getLinkedException() != null && e.getLinkedException().getLocalizedMessage() != null)
            result.addMessage(e.getLinkedException().getLocalizedMessage());
        return result;
    }
    return new ValidationResult(true);

}

From source file:it.polimi.modaclouds.qos_models.util.XMLHelper.java

public static <T> ValidationResult validate(FileInputStream xmlPath, Class<T> targetClass) {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Unmarshaller unmarshaller;
    ValidationResult result;/*ww w.  j av  a 2 s  .c  o  m*/
    try {
        Schema schema = schemaFactory.newSchema();
        unmarshaller = JAXBContext.newInstance(targetClass).createUnmarshaller();
        unmarshaller.setSchema(schema);
    } catch (SAXException | JAXBException e) {
        result = new ValidationResult(false);
        result.addMessage("Error occured in creating the schema");
        result.addMessage(e.getLocalizedMessage());
        return result;
    }
    try {
        unmarshaller.unmarshal(xmlPath);
    } catch (JAXBException e) {
        result = new ValidationResult(false);
        if (e.getMessage() != null)
            result.addMessage(e.getLocalizedMessage());
        if (e.getLinkedException() != null && e.getLinkedException().getLocalizedMessage() != null)
            result.addMessage(e.getLinkedException().getLocalizedMessage());
        return result;
    }
    return new ValidationResult(true);

}

From source file:it.polimi.modaclouds.qos_models.util.XMLHelper.java

public static <T> ValidationResult validate(InputStream xmlStream, Class<T> targetClass) {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Unmarshaller unmarshaller;
    ValidationResult result;//ww  w .  j  a  va 2s .  c  o m
    try {
        Schema schema = schemaFactory.newSchema();
        unmarshaller = JAXBContext.newInstance(targetClass).createUnmarshaller();
        unmarshaller.setSchema(schema);
    } catch (SAXException | JAXBException e) {
        result = new ValidationResult(false);
        result.addMessage("Error occured in creating the schema");
        result.addMessage(e.getLocalizedMessage());
        return result;
    }
    try {
        unmarshaller.unmarshal(xmlStream);
    } catch (JAXBException e) {
        result = new ValidationResult(false);
        if (e.getMessage() != null)
            result.addMessage(e.getLocalizedMessage());
        if (e.getLinkedException() != null && e.getLinkedException().getLocalizedMessage() != null)
            result.addMessage(e.getLinkedException().getLocalizedMessage());
        return result;
    }
    return new ValidationResult(true);

}

From source file:org.opennms.netmgt.ackd.readers.HypericAckProcessor.java

/**
 * <p>parseHypericAlerts</p>
 *
 * @param reader a {@link java.io.Reader} object.
 * @return a {@link java.util.List} object.
 * @throws javax.xml.bind.JAXBException if any.
 * @throws javax.xml.stream.XMLStreamException if any.
 *///from   ww  w.j  a  v  a 2  s . c o  m
public static List<HypericAlertStatus> parseHypericAlerts(Reader reader)
        throws JAXBException, XMLStreamException {
    List<HypericAlertStatus> retval = new ArrayList<HypericAlertStatus>();

    // Instantiate a JAXB context to parse the alert status
    JAXBContext context = JAXBContext
            .newInstance(new Class[] { HypericAlertStatuses.class, HypericAlertStatus.class });
    XMLInputFactory xmlif = XMLInputFactory.newInstance();
    XMLEventReader xmler = xmlif.createXMLEventReader(reader);
    EventFilter filter = new EventFilter() {
        @Override
        public boolean accept(XMLEvent event) {
            return event.isStartElement();
        }
    };
    XMLEventReader xmlfer = xmlif.createFilteredReader(xmler, filter);
    // Read up until the beginning of the root element
    StartElement startElement = (StartElement) xmlfer.nextEvent();
    // Fetch the root element name for {@link HypericAlertStatus} objects
    String rootElementName = context.createJAXBIntrospector().getElementName(new HypericAlertStatuses())
            .getLocalPart();
    if (rootElementName.equals(startElement.getName().getLocalPart())) {
        Unmarshaller unmarshaller = context.createUnmarshaller();
        // Use StAX to pull parse the incoming alert statuses
        while (xmlfer.peek() != null) {
            Object object = unmarshaller.unmarshal(xmler);
            if (object instanceof HypericAlertStatus) {
                HypericAlertStatus alertStatus = (HypericAlertStatus) object;
                retval.add(alertStatus);
            }
        }
    } else {
        // Try to pull in the HTTP response to give the user a better idea of what went wrong
        StringBuffer errorContent = new StringBuffer();
        LineNumberReader lineReader = new LineNumberReader(reader);
        try {
            String line;
            while (true) {
                line = lineReader.readLine();
                if (line == null) {
                    break;
                } else {
                    errorContent.append(line.trim());
                }
            }
        } catch (IOException e) {
            errorContent.append("Exception while trying to print out message content: " + e.getMessage());
        }

        // Throw an exception and include the erroneous HTTP response in the exception text
        throw new JAXBException("Found wrong root element in Hyperic XML document, expected: \""
                + rootElementName + "\", found \"" + startElement.getName().getLocalPart() + "\"\n"
                + errorContent.toString());
    }
    return retval;
}

From source file:com.aurel.track.exchange.docx.exporter.NumberingUtil.java

static void setNumbering(WordprocessingMLPackage newPkg) {
    java.io.InputStream is = null;
    try {/* w ww . java  2 s . com*/
        is = ResourceUtils.getResource("com/aurel/track/exchange/docx/exporter/numbering.xml");
    } catch (IOException e) {
        LOGGER.error("Getting the KnownStyles.xml failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    JAXBContext jc = Context.jc;
    Unmarshaller unmarshaller = null;
    try {
        unmarshaller = jc.createUnmarshaller();
    } catch (JAXBException e) {
        LOGGER.error("Creating a JAXB unmarshaller failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    try {
        unmarshaller.setEventHandler(new JaxbValidationEventHandler());
    } catch (JAXBException e) {
        LOGGER.error("Setting the event handler for JAXB unmarshaller failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    Numbering numbering = null;
    try {
        numbering = (Numbering) unmarshaller.unmarshal(is);
    } catch (JAXBException e) {
        LOGGER.error("Unmarshalling the numbering.xml failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    NumberingDefinitionsPart numberingDefinitionsPart = null;
    try {
        numberingDefinitionsPart = new NumberingDefinitionsPart();
    } catch (InvalidFormatException e) {
        LOGGER.error("Creating the styles definition part failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    numberingDefinitionsPart.setPackage(newPkg);
    numberingDefinitionsPart.setJaxbElement(numbering);
    try {
        newPkg.getMainDocumentPart().addTargetPart(numberingDefinitionsPart);
    } catch (InvalidFormatException e) {
        LOGGER.error("Adding the target part to MainDocumentPart failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
}

From source file:org.eclipse.winery.repository.client.WineryRepositoryClient.java

/**
 * Tries to retrieve a TDefinitions from the given resource / encoded(ns) /
 * encoded(localPart)//from  w  ww .j a  v a  2  s.c  o m
 *
 * @return null if 404 or other error
 */
private static TDefinitions getDefinitions(WebResource componentListResource, String ns, String localPart) {
    // we need double encoding as the client decodes the URL once
    String nsEncoded = Util.DoubleURLencode(ns);
    String idEncoded = Util.DoubleURLencode(localPart);

    WebResource instanceResource = componentListResource.path(nsEncoded).path(idEncoded);

    // TODO: org.eclipse.winery.repository.resources.AbstractComponentInstanceResource.getDefinitionsWithAssociatedThings() could be used to do the resolving at the server

    ClientResponse response = instanceResource.accept(MimeTypes.MIMETYPE_TOSCA_DEFINITIONS)
            .get(ClientResponse.class);
    if (response.getStatus() != 200) {
        // also handles 404
        return null;
    }

    TDefinitions definitions;
    try {
        Unmarshaller um = WineryRepositoryClient.createUnmarshaller();
        definitions = (TDefinitions) um.unmarshal(response.getEntityInputStream());
    } catch (JAXBException e) {
        LOGGER.error("Could not umarshal TDefinitions", e);
        // try next service
        return null;
    }
    return definitions;
}

From source file:com.cloudera.api.model.ApiModelTest.java

static <T> T xmlToObject(String text, Class<T> type)
        throws JAXBException, UnsupportedEncodingException, IllegalAccessException, InstantiationException {
    JAXBContext jc = JAXBContext.newInstance(type);
    Unmarshaller um = jc.createUnmarshaller();
    ByteArrayInputStream bais = new ByteArrayInputStream(text.getBytes(TEXT_ENCODING));
    Object res = um.unmarshal(bais);
    return type.cast(res);
}

From source file:fr.cls.atoll.motu.processor.wps.TestServiceMetadata.java

public static void testLoadOGCServiceMetadata() {
    // String xmlFile =
    // "J:/dev/atoll-v2/atoll-motu/atoll-motu-processor/src/test/resources/xml/TestServiceMetadata.xml";
    String xmlFile = "C:/Documents and Settings/dearith/Mes documents/Atoll/SchemaIso/TestServiceMetadataOK.xml";

    String schemaPath = "schema/iso19139";

    try {//  ww w  .  ja  va  2 s .  c  om
        List<String> errors = validateServiceMetadataFromString(xmlFile, schemaPath);
        if (errors.size() > 0) {
            StringBuffer stringBuffer = new StringBuffer();
            for (String str : errors) {
                stringBuffer.append(str);
                stringBuffer.append("\n");
            }
            throw new MotuException(String.format("ERROR - XML file '%s' is not valid - See errors below:\n%s",
                    xmlFile, stringBuffer.toString()));
        } else {
            System.out.println(String.format("XML file '%s' is valid", xmlFile));
        }

    } catch (MotuException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    InputStream in = null;
    try {
        in = Organizer.getUriAsInputStream(xmlFile);
    } catch (MotuException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    JAXBContext jc = null;
    try {
        // jc = JAXBContext.newInstance("org.isotc211.iso19139.d_2006_05_04.srv");
        // jc = JAXBContext.newInstance("org.isotc211.iso19139.d_2006_05_04.srv");
        jc = JAXBContext
                .newInstance(new Class[] { org.isotc211.iso19139.d_2006_05_04.srv.ObjectFactory.class });
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Source srcFile = new StreamSource(xmlFile);
        JAXBElement<?> element = (JAXBElement<?>) unmarshaller.unmarshal(srcFile);
        // JAXBElement<?> element = (JAXBElement<?>) unmarshaller.unmarshal(in);
        SVServiceIdentificationType serviceIdentificationType = (SVServiceIdentificationType) element
                .getValue();
        // serviceIdentificationType = (SVServiceIdentificationType) unmarshaller.unmarshal(in);
        System.out.println(serviceIdentificationType.toString());

        List<SVOperationMetadataPropertyType> operationMetadataPropertyTypeList = serviceIdentificationType
                .getContainsOperations();

        for (SVOperationMetadataPropertyType operationMetadataPropertyType : operationMetadataPropertyTypeList) {

            SVOperationMetadataType operationMetadataType = operationMetadataPropertyType
                    .getSVOperationMetadata();
            System.out.println("---------------------------------------------");
            if (operationMetadataType == null) {
                continue;
            }
            System.out.println(operationMetadataType.getOperationName().getCharacterString().getValue());
            System.out.println(operationMetadataType.getInvocationName().getCharacterString().getValue());
            System.out.println(operationMetadataType.getOperationDescription().getCharacterString().getValue());

            CIOnlineResourcePropertyType onlineResourcePropertyType = operationMetadataType.getConnectPoint()
                    .get(0);
            if (onlineResourcePropertyType != null) {
                System.out.println(operationMetadataType.getConnectPoint().get(0).getCIOnlineResource()
                        .getLinkage().getURL());
            }

            List<SVParameterPropertyType> parameterPropertyTypeList = operationMetadataType.getParameters();

            for (SVParameterPropertyType parameterPropertyType : parameterPropertyTypeList) {
                SVParameterType parameterType = parameterPropertyType.getSVParameter();

                if (parameterType.getName().getAName().getCharacterString() != null) {
                    System.out.println(parameterType.getName().getAName().getCharacterString().getValue());
                } else {
                    System.out.println("WARNING - A parameter has no name");

                }
                if (parameterType.getDescription() != null) {
                    if (parameterType.getDescription().getCharacterString() != null) {
                        System.out.println(parameterType.getDescription().getCharacterString().getValue());
                    } else {
                        System.out.println("WARNING - A parameter has no description");

                    }
                } else {
                    System.out.println("WARNING - A parameter has no description");

                }
            }

        }
        FileWriter writer = new FileWriter("c:/tempVFS/test.xml");

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(element, writer);

        writer.flush();
        writer.close();

        System.out.println("End testLoadOGCServiceMetadata");
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.virtualparadigm.packman.processor.JPackageManagerBU.java

private static Collection<Package> unmarshallFromFile(String inputFilePath) {
    List<Package> installPackageList = null;
    try {/*from  w  w  w .ja  v a2s.co m*/
        File inputFile = new File(inputFilePath);
        if (inputFile.exists()) {
            Unmarshaller unmarashaller = jaxbContext.createUnmarshaller();
            List<String> lines = FileUtils.readLines(new File(inputFilePath));
            installPackageList = new ArrayList<Package>();
            for (String line : lines) {
                installPackageList.add((Package) unmarashaller.unmarshal(new StringReader(line)));
            }
        }
    } catch (Exception e) {
        logger.error("", e);
        //            e.printStackTrace();
    }
    return installPackageList;
}

From source file:com.evolveum.midpoint.model.client.ModelClientUtil.java

public static <O> O unmarshallResource(String path) throws JAXBException, FileNotFoundException {
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

    InputStream is = null;//from   w  w  w  .  j  av a 2  s.  c  o  m
    JAXBElement<O> element = null;
    try {
        is = ModelClientUtil.class.getClassLoader().getResourceAsStream(path);
        if (is == null) {
            throw new FileNotFoundException("System resource " + path + " was not found");
        }
        element = (JAXBElement<O>) unmarshaller.unmarshal(is);
    } finally {
        if (is != null) {
            IOUtils.closeQuietly(is);
        }
    }
    if (element == null) {
        return null;
    }
    return element.getValue();
}