Example usage for javax.xml.bind JAXBElement getValue

List of usage examples for javax.xml.bind JAXBElement getValue

Introduction

In this page you can find the example usage for javax.xml.bind JAXBElement getValue.

Prototype

public T getValue() 

Source Link

Document

Return the content model and attribute values for this element.

See #isNil() for a description of a property constraint when this value is null

Usage

From source file:cosmos.results.integration.CosmosIntegrationSetup.java

@SuppressWarnings({ "rawtypes", "unchecked" })
protected static MediaWikiType loadWiki(int num) throws Exception {
    initializeJaxb();/*ww  w  . j ava2  s  .  co  m*/

    Unmarshaller unmarshaller = context.createUnmarshaller();

    InputStream is = CosmosIntegrationSetup.class.getResourceAsStream(ARTICLE_BASE + num + ARTICLE_SUFFIX);

    Assert.assertNotNull(is);

    GZIPInputStream gzip = new GZIPInputStream(is);
    Object o = unmarshaller.unmarshal(gzip);

    Assert.assertEquals(JAXBElement.class, o.getClass());
    Assert.assertEquals(MediaWikiType.class, ((JAXBElement) o).getDeclaredType());

    JAXBElement<MediaWikiType> jaxb = (JAXBElement<MediaWikiType>) o;

    return jaxb.getValue();
}

From source file:edu.lternet.pasta.common.EmlUtility.java

/**
 * Parses the provided EML 2.1.0 {@code <access>} element string and
 * returns a corresponding JAXB object.//from www .  ja v  a  2 s .c o m
 *
 * @param accessString
 *            the {@code <access>} element string.
 * @return a JAXB object corresponding to the provided string.
 *
 * @throws IllegalArgumentException
 *             with a {@linkplain JAXBException} as the cause.
 */
@SuppressWarnings("unchecked")
public static AccessType getAccessType2_1_0(String accessString) {

    try {
        String packageName = AccessType.class.getPackage().getName();
        JAXBContext jc = JAXBContext.newInstance(packageName);
        Unmarshaller u = jc.createUnmarshaller();
        StringReader reader = new StringReader(accessString);

        JAXBElement<AccessType> jaxb = (JAXBElement<AccessType>) u.unmarshal(reader);

        return jaxb.getValue();
    } catch (JAXBException e) {
        throw new IllegalArgumentException(e);
    }

}

From source file:JALPTest.java

/**
 * Unmarshals an xml file into an ApplicationMetadataType.
 *
 * @param path   the path to the xml file to be unmarshalled
 * @return   the created ApplicationMetadataType
 * @throws Exception/*from w  w  w.  j a va  2 s . c  o m*/
 */
private static ApplicationMetadataType readXML(String path) throws Exception {
    JAXBContext jc = JAXBContext
            .newInstance("com.tresys.jalop.schemas.mil.dod.jalop_1_0.applicationmetadatatypes");
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    JAXBElement<ApplicationMetadataType> jaxAmt = (JAXBElement<ApplicationMetadataType>) unmarshaller
            .unmarshal(new File(path));
    return jaxAmt.getValue();
}

From source file:com.netxforge.oss2.core.xml.JaxbUtils.java

public static <T> T unmarshal(final Class<T> clazz, final InputSource inputSource,
        final JAXBContext jaxbContext, final boolean validate) {
    final Unmarshaller um = getUnmarshallerFor(clazz, jaxbContext, validate);

    LogUtils.tracef(clazz, "unmarshalling class %s from input source %s with unmarshaller %s",
            clazz.getSimpleName(), inputSource, um);
    try {/*  w ww.  j a va  2  s  .c om*/
        final XMLFilter filter = getXMLFilterForClass(clazz);
        final SAXSource source = new SAXSource(filter, inputSource);

        um.setEventHandler(new LoggingValidationEventHandler(clazz));

        final JAXBElement<T> element = um.unmarshal(source, clazz);
        return element.getValue();
    } catch (final SAXException e) {
        throw EXCEPTION_TRANSLATOR.translate("creating an XML reader object", e);
    } catch (final JAXBException e) {
        throw EXCEPTION_TRANSLATOR.translate("unmarshalling an object (" + clazz.getSimpleName() + ")", e);
    }
}

From source file:ee.ria.xroad.proxy.util.MetaserviceTestUtil.java

/** Try to extract a single element of type T from the Soap Body, of class clazz.
 * @param body the {@link SOAPBody}/*from   ww  w .ja  v  a  2s. com*/
 * @param clazz the class of type T
 * @param unmarshallerSupplier a {@link Supplier} for the unmarshaller. Needed if this util class does not
 *                             know of the class you want to unmarshall
 * @param <T> the {@link JAXBElement} value to extract, like {@link ee.ria.xroad.common.metadata.MethodListType}
 * @return the resulting element of type T
 * @throws JAXBException if unexpected errors occur during unmarshalling
 */
public static <T> T verifyAndGetSingleBodyElementOfType(SOAPBody body, Class<T> clazz,
        Supplier<Unmarshaller> unmarshallerSupplier) throws JAXBException {

    NodeList list = body.getChildNodes();

    List<Element> elements = new ArrayList<>();
    for (int i = 0; i < list.getLength(); i++) {
        Node node = list.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            elements.add((Element) node);
        }
    }

    assertThat("Was expecting a single element", elements.size(), is(1));
    JAXBElement<T> element = unmarshallerSupplier.get().unmarshal(elements.get(0), clazz);
    return element.getValue();
}

From source file:org.eclipse.mylyn.internal.hudson.core.client.RestfulHudsonClient.java

public static <T> T unmarshal(Node node, Class<T> clazz) throws JAXBException {
    JAXBContext ctx = JAXBContext.newInstance(clazz);

    Unmarshaller unmarshaller = ctx.createUnmarshaller();

    JAXBElement<T> hudsonElement = unmarshaller.unmarshal(node, clazz);
    return hudsonElement.getValue();
}

From source file:be.fedict.eid.dss.ws.DSSUtil.java

@SuppressWarnings("unchecked")
public static ReturnStoredDocument getReturnStoredDocument(Element returnStoredDocumentElement)
        throws JAXBException {

    JAXBElement<ReturnStoredDocument> jaxbElement = (JAXBElement<ReturnStoredDocument>) artifactUnmarshaller
            .unmarshal(returnStoredDocumentElement);
    return jaxbElement.getValue();
}

From source file:ee.ria.xroad.common.hashchain.HashChainVerifier.java

@SuppressWarnings("unchecked")
private static HashChainType parseHashChain(InputStream xml) throws Exception {
    Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();
    JAXBElement<HashChainType> element = (JAXBElement<HashChainType>) unmarshaller.unmarshal(xml);

    HashChainValidator.validate(new JAXBSource(jaxbCtx, element));

    return element.getValue();
}

From source file:ee.ria.xroad.common.hashchain.HashChainVerifier.java

@SuppressWarnings("unchecked")
private static HashChainResultType parseHashChainResult(InputStream xml) throws Exception {
    Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();
    JAXBElement<HashChainResultType> element = (JAXBElement<HashChainResultType>) unmarshaller.unmarshal(xml);

    HashChainValidator.validate(new JAXBSource(jaxbCtx, element));

    return element.getValue();
}

From source file:be.e_contract.dssp.client.SignResponseVerifier.java

/**
 * Checks the signature on the SignResponse browser POST message.
 * /*from w w  w.j  av a2s.  c o  m*/
 * @param signResponseMessage
 *            the SignResponse message.
 * @param session
 *            the session object.
 * @return the verification result object.
 * @throws JAXBException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws MarshalException
 * @throws XMLSignatureException
 * @throws Base64DecodingException
 * @throws UserCancelException
 * @throws ClientRuntimeException
 * @throws SubjectNotAuthorizedException
 */
public static SignResponseVerificationResult checkSignResponse(String signResponseMessage,
        DigitalSignatureServiceSession session) throws JAXBException, ParserConfigurationException,
        SAXException, IOException, MarshalException, XMLSignatureException, Base64DecodingException,
        UserCancelException, ClientRuntimeException, SubjectNotAuthorizedException {
    if (null == session) {
        throw new IllegalArgumentException("missing session");
    }

    byte[] decodedSignResponseMessage;
    try {
        decodedSignResponseMessage = Base64.decode(signResponseMessage);
    } catch (Base64DecodingException e) {
        throw new SecurityException("no Base64");
    }
    // JAXB parsing
    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class,
            be.e_contract.dssp.ws.jaxb.dss.async.ObjectFactory.class,
            be.e_contract.dssp.ws.jaxb.wsa.ObjectFactory.class,
            be.e_contract.dssp.ws.jaxb.wsu.ObjectFactory.class);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    SignResponse signResponse;
    try {
        signResponse = (SignResponse) unmarshaller
                .unmarshal(new ByteArrayInputStream(decodedSignResponseMessage));
    } catch (UnmarshalException e) {
        throw new SecurityException("no valid SignResponse XML");
    }

    // DOM parsing
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    InputStream signResponseInputStream = new ByteArrayInputStream(decodedSignResponseMessage);
    Document signResponseDocument = documentBuilder.parse(signResponseInputStream);

    // signature verification
    NodeList signatureNodeList = signResponseDocument
            .getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Signature");
    if (signatureNodeList.getLength() != 1) {
        throw new SecurityException("requires 1 ds:Signature element");
    }
    Element signatureElement = (Element) signatureNodeList.item(0);
    SecurityTokenKeySelector keySelector = new SecurityTokenKeySelector(session.getKey());
    DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement);
    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM");
    XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
    boolean validSignature = xmlSignature.validate(domValidateContext);
    if (false == validSignature) {
        throw new SecurityException("invalid ds:Signature");
    }

    // verify content
    String responseId = null;
    RelatesToType relatesTo = null;
    AttributedURIType to = null;
    TimestampType timestamp = null;
    String signerIdentity = null;
    AnyType optionalOutputs = signResponse.getOptionalOutputs();
    List<Object> optionalOutputsList = optionalOutputs.getAny();
    for (Object optionalOutputObject : optionalOutputsList) {
        LOG.debug("optional output object type: " + optionalOutputObject.getClass().getName());
        if (optionalOutputObject instanceof JAXBElement) {
            JAXBElement optionalOutputElement = (JAXBElement) optionalOutputObject;
            LOG.debug("optional output name: " + optionalOutputElement.getName());
            LOG.debug("optional output value type: " + optionalOutputElement.getValue().getClass().getName());
            if (RESPONSE_ID_QNAME.equals(optionalOutputElement.getName())) {
                responseId = (String) optionalOutputElement.getValue();
            } else if (optionalOutputElement.getValue() instanceof RelatesToType) {
                relatesTo = (RelatesToType) optionalOutputElement.getValue();
            } else if (TO_QNAME.equals(optionalOutputElement.getName())) {
                to = (AttributedURIType) optionalOutputElement.getValue();
            } else if (optionalOutputElement.getValue() instanceof TimestampType) {
                timestamp = (TimestampType) optionalOutputElement.getValue();
            } else if (optionalOutputElement.getValue() instanceof NameIdentifierType) {
                NameIdentifierType nameIdentifier = (NameIdentifierType) optionalOutputElement.getValue();
                signerIdentity = nameIdentifier.getValue();
            }
        }
    }

    Result result = signResponse.getResult();
    LOG.debug("result major: " + result.getResultMajor());
    LOG.debug("result minor: " + result.getResultMinor());
    if (DigitalSignatureServiceConstants.REQUESTER_ERROR_RESULT_MAJOR.equals(result.getResultMajor())) {
        if (DigitalSignatureServiceConstants.USER_CANCEL_RESULT_MINOR.equals(result.getResultMinor())) {
            throw new UserCancelException();
        }
        if (DigitalSignatureServiceConstants.CLIENT_RUNTIME_RESULT_MINOR.equals(result.getResultMinor())) {
            throw new ClientRuntimeException();
        }
        if (DigitalSignatureServiceConstants.SUBJECT_NOT_AUTHORIZED_RESULT_MINOR
                .equals(result.getResultMinor())) {
            throw new SubjectNotAuthorizedException(signerIdentity);
        }
    }
    if (false == DigitalSignatureServiceConstants.PENDING_RESULT_MAJOR.equals(result.getResultMajor())) {
        throw new SecurityException("invalid dss:ResultMajor");
    }

    if (null == responseId) {
        throw new SecurityException("missing async:ResponseID");
    }
    if (false == responseId.equals(session.getResponseId())) {
        throw new SecurityException("invalid async:ResponseID");
    }

    if (null == relatesTo) {
        throw new SecurityException("missing wsa:RelatesTo");
    }
    if (false == session.getInResponseTo().equals(relatesTo.getValue())) {
        throw new SecurityException("invalid wsa:RelatesTo");
    }

    if (null == to) {
        throw new SecurityException("missing wsa:To");
    }
    if (false == session.getDestination().equals(to.getValue())) {
        throw new SecurityException("invalid wsa:To");
    }

    if (null == timestamp) {
        throw new SecurityException("missing wsu:Timestamp");
    }
    AttributedDateTime expires = timestamp.getExpires();
    if (null == expires) {
        throw new SecurityException("missing wsu:Timestamp/wsu:Expires");
    }
    DateTime expiresDateTime = new DateTime(expires.getValue());
    DateTime now = new DateTime();
    if (now.isAfter(expiresDateTime)) {
        throw new SecurityException("wsu:Timestamp expired");
    }

    session.setSignResponseVerified(true);

    SignResponseVerificationResult signResponseVerificationResult = new SignResponseVerificationResult(
            signerIdentity);
    return signResponseVerificationResult;
}