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:be.agiv.security.client.RSTSClient.java

/**
 * Retrieves a new security token from the R-STS WS-Trust web service using
 * the given IP-STS security token. The security token retrieved from the
 * R-STS always applies to a certain AGIV web service. The location of this
 * AGIV web service is also passed as parameter.
 * //from w  w  w . j  a v a2 s .c om
 * @param ipStsSecurityToken
 *            the IP-STS security token.
 * @param appliesTo
 *            the WS-SecureConversation enabled web service to which the
 *            R-STS security token should apply.
 * @return the R-STS security token to be used by the service Secure
 *         Conversation.
 */
public SecurityToken getSecurityToken(SecurityToken ipStsSecurityToken, String appliesTo) {
    RequestSecurityTokenType requestSecurityToken = this.objectFactory.createRequestSecurityTokenType();
    List<Object> requestSecurityTokenContent = requestSecurityToken.getAny();
    requestSecurityTokenContent.add(this.objectFactory.createRequestType(WSConstants.ISSUE_REQUEST_TYPE));

    AppliesTo jaxbAppliesTo = this.policyObjectFactory.createAppliesTo();
    EndpointReferenceType endpointReference = this.addrObjectFactory.createEndpointReferenceType();
    AttributedURIType address = this.addrObjectFactory.createAttributedURIType();
    address.setValue(appliesTo);
    endpointReference.setAddress(address);
    jaxbAppliesTo.getAny().add(this.addrObjectFactory.createEndpointReference(endpointReference));
    requestSecurityTokenContent.add(jaxbAppliesTo);

    BindingProvider bindingProvider = (BindingProvider) this.port;
    this.wsAddressingHandler.setAddressing(WSConstants.WS_TRUST_ISSUE_ACTION, this.location);
    this.wsSecurityHandler.setKey(ipStsSecurityToken.getKey(), ipStsSecurityToken.getAttachedReference(),
            ipStsSecurityToken.getToken());

    RequestSecurityTokenResponseCollectionType requestSecurityTokenResponseCollection = this.port
            .requestSecurityToken(requestSecurityToken);

    SecurityToken securityToken = new SecurityToken();

    List<RequestSecurityTokenResponseType> requestSecurityTokenResponseList = requestSecurityTokenResponseCollection
            .getRequestSecurityTokenResponse();
    RequestSecurityTokenResponseType requestSecurityTokenResponse = requestSecurityTokenResponseList.get(0);
    List<Object> requestSecurityTokenResponseContent = requestSecurityTokenResponse.getAny();
    for (Object contentObject : requestSecurityTokenResponseContent) {
        LOG.debug("content object: " + contentObject.getClass().getName());
        if (contentObject instanceof Element) {
            Element contentElement = (Element) contentObject;
            LOG.debug("element name: " + contentElement.getLocalName());
        }
        if (contentObject instanceof JAXBElement) {
            JAXBElement jaxbElement = (JAXBElement) contentObject;
            QName qname = jaxbElement.getName();
            LOG.debug("JAXB qname: " + qname);
            if (WSConstants.LIFETIME_QNAME.equals(qname)) {
                LOG.debug("trust:Lifetime");
                LifetimeType lifetime = (LifetimeType) jaxbElement.getValue();
                String createdValue = lifetime.getCreated().getValue();
                DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTimeParser();
                DateTime created = dateTimeFormatter.parseDateTime(createdValue);
                securityToken.setCreated(created.toDate());
                String expiresString = lifetime.getExpires().getValue();
                DateTime expires = dateTimeFormatter.parseDateTime(expiresString);
                securityToken.setExpires(expires.toDate());
            } else if (WSConstants.REQUESTED_ATTACHED_REFERENCE_QNAME.equals(qname)) {
                RequestedReferenceType requestedReference = (RequestedReferenceType) jaxbElement.getValue();
                SecurityTokenReferenceType securityTokenReference = requestedReference
                        .getSecurityTokenReference();
                List<Object> securityTokenReferenceContent = securityTokenReference.getAny();
                for (Object securityTokenReferenceObject : securityTokenReferenceContent) {
                    LOG.debug("SecurityTokenReference object: "
                            + securityTokenReferenceObject.getClass().getName());
                    if (securityTokenReferenceObject instanceof JAXBElement) {
                        JAXBElement securityTokenReferenceElement = (JAXBElement) securityTokenReferenceObject;
                        LOG.debug("SecurityTokenReference element: " + securityTokenReferenceElement.getName());
                        if (securityTokenReferenceElement.getName().equals(WSConstants.KEY_IDENTIFIER_QNAME)) {
                            KeyIdentifierType keyIdentifier = (KeyIdentifierType) securityTokenReferenceElement
                                    .getValue();
                            String tokenIdentifier = keyIdentifier.getValue();
                            securityToken.setAttachedReference(tokenIdentifier);
                        }
                    }
                }
            } else if (WSConstants.REQUESTED_PROOF_TOKEN_QNAME.equals(qname)) {
                RequestedProofTokenType requestedProofToken = (RequestedProofTokenType) jaxbElement.getValue();
                Object requestedProofTokenContent = requestedProofToken.getAny();
                LOG.debug("requested proof token content: " + requestedProofTokenContent.getClass().getName());
                if (requestedProofTokenContent instanceof JAXBElement) {
                    JAXBElement requestedProofTokenElement = (JAXBElement) requestedProofTokenContent;
                    LOG.debug("requested proof token element: " + requestedProofTokenElement.getName());
                    if (WSConstants.BINARY_SECRET_QNAME.equals(requestedProofTokenElement.getName())) {
                        BinarySecretType serverBinarySecret = (BinarySecretType) requestedProofTokenElement
                                .getValue();
                        byte[] serverSecret = serverBinarySecret.getValue();
                        securityToken.setKey(serverSecret);
                    }
                }
            }
        }
    }

    Element requestedSecurityToken = this.wsTrustHandler.getRequestedSecurityToken();
    securityToken.setToken(requestedSecurityToken);
    securityToken.setRealm(appliesTo);
    securityToken.setStsLocation(this.location);
    securityToken.setParentSecurityToken(ipStsSecurityToken);

    return securityToken;
}

From source file:eu.dasish.annotation.backend.rest.AnnotationResourceTest.java

@Test
public void testUpdateAnnotation() throws NotInDataBaseException, IOException, ForbiddenException {
    System.out.println("test updateAnnotation");

    final Annotation annotation = (new TestInstances("/backend/api")).getAnnotationOne();
    annotation.getPermissions().setPublic(Access.READ);
    annotation.setHeadline("updated annotation 1");
    annotation.getPermissions().getPermission().get(1).setLevel(Access.WRITE);
    AnnotationBody ab = new AnnotationBody();
    TextBody tb = new TextBody();
    ab.setTextBody(tb);//from  w w w.  j a  v  a 2s  .  c  o  m
    tb.setMimeType("text/plain");
    tb.setBody("some text body l");
    annotation.setBody(ab);

    final ResponseBody mockEnvelope = new ResponseBody();
    final ActionList actionList = new ActionList();
    mockEnvelope.setAnnotation(annotation);
    mockEnvelope.setActionList(actionList);

    annotationResource.setHttpServletRequest(mockRequest);
    mockRequest.setRemoteUser("twagoo@mpi.nl");
    mockRequest.setContextPath("/backend");
    mockRequest.setServletPath("/api");
    final UUID externalId = UUID.fromString("00000000-0000-0000-0000-000000000021");

    //  Number annotationID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(externalIdentifier), Resource.ANNOTATION);
    //  if (principalID.equals(dbIntegrityService.getAnnotationOwnerID(annotationID)) || dbIntegrityService.getTypeOfPrincipalAccount(principalID).equals(admin)) {
    //  int updatedRows = dbIntegrityService.updateAnnotation(annotation);
    //  return new ObjectFactory().createResponseBody(dbIntegrityService.makeAnnotationResponseEnvelope(annotationID));

    mockeryRest.checking(new Expectations() {
        {
            oneOf(mockDbDispatcher).setResourcesPaths("/backend/api");

            oneOf(mockDbDispatcher).getPrincipalInternalIDFromRemoteID("twagoo@mpi.nl");
            will(returnValue(1));

            oneOf(mockDbDispatcher).getResourceInternalIdentifier(externalId, Resource.ANNOTATION);
            will(returnValue(1));

            oneOf(mockDbDispatcher).getAnnotationOwnerID(1);
            will(returnValue(1));

            oneOf(mockDbDispatcher).canDo(Access.WRITE, 1, 1, Resource.ANNOTATION);
            will(returnValue(true));

            oneOf(mockDbDispatcher).updateAnnotation(annotation, "twagoo@mpi.nl");
            will(returnValue(1));

            oneOf(mockDbDispatcher).makeAnnotationResponseEnvelope(1);
            will(returnValue(mockEnvelope));

        }
    });

    JAXBElement<ResponseBody> result = annotationResource
            .updateAnnotation("00000000-0000-0000-0000-000000000021", annotation);
    Annotation newAnnotation = result.getValue().getAnnotation();
    assertEquals(annotation.getOwnerHref(), newAnnotation.getOwnerHref());
    assertEquals(annotation.getId(), newAnnotation.getId());
    assertEquals(annotation.getHref(), newAnnotation.getHref());
    assertEquals("updated annotation 1", newAnnotation.getHeadline());
    assertEquals("text/plain", newAnnotation.getBody().getTextBody().getMimeType());
    assertEquals("some text body l", newAnnotation.getBody().getTextBody().getBody());
    assertEquals(Access.WRITE, annotation.getPermissions().getPermission().get(1).getLevel());
    assertEquals(Access.READ, annotation.getPermissions().getPublic());
}

From source file:edu.harvard.i2b2.patientMapping.ui.AdminToolSetPasswordJPanel.java

/** Creates new form PatientMappingJPanel */
public AdminToolSetPasswordJPanel() {
    initComponents();/*  www.j a v  a2  s .  c  om*/

    String userID = UserInfoBean.getInstance().getUserName();
    //jUserIdComboBox.addItem(projectID);
    jUserIdComboBox.setModel(new javax.swing.DefaultComboBoxModel());//new String[] {projectID}));
    //jUserIdComboBox.setEditable(true);

    if (UserInfoBean.getInstance().isAdmin()) {
        jUserIdComboBox.setEditable(true);
        if (users == null) {
            users = new ArrayList<String>();
            PmServiceController pms = new PmServiceController();
            try {
                PasswordType ptype = new PasswordType();
                ptype.setIsToken(UserInfoBean.getInstance().getUserPasswordIsToken());
                ptype.setTokenMsTimeout(UserInfoBean.getInstance().getUserPasswordTimeout());
                ptype.setValue(UserInfoBean.getInstance().getUserPassword());
                String response = pms.getUserInfo(UserInfoBean.getInstance().getUserName(), ptype,
                        UserInfoBean.getInstance().getSelectedProjectUrl(),
                        UserInfoBean.getInstance().getUserDomain(), false,
                        UserInfoBean.getInstance().getProjectId());

                ////
                JAXBUtil jaxbUtil = new JAXBUtil(new String[] { "edu.harvard.i2b2.crcxmljaxb.datavo.pm", //$NON-NLS-1$
                        "edu.harvard.i2b2.crcxmljaxb.datavo.i2b2message" //$NON-NLS-1$
                });
                JAXBElement jaxbElement = jaxbUtil.unMashallFromString(response);
                ResponseMessageType responseMessageType = (ResponseMessageType) jaxbElement.getValue();

                String procStatus = responseMessageType.getResponseHeader().getResultStatus().getStatus()
                        .getType();
                //String procMessage = responseMessageType.getResponseHeader().getResultStatus().getStatus().getValue();

                //String serverVersion = responseMessageType.getMessageHeader()
                //.getSendingApplication().getApplicationVersion();
                //System.setProperty("serverVersion", serverVersion);

                if (procStatus.equals("ERROR")) { //$NON-NLS-1$
                    //setMsg(procMessage);            
                } else if (procStatus.equals("WARNING")) { //$NON-NLS-1$
                    //setMsg(procMessage);
                } else {
                    BodyType bodyType = responseMessageType.getMessageBody();
                    JAXBUnWrapHelper helper = new JAXBUnWrapHelper();
                    RolesType rolesType = (RolesType) helper.getObjectByClass(bodyType.getAny(),
                            RolesType.class);
                    ArrayList<String> tmpArr = new ArrayList<String>();
                    for (int i = 0; i < rolesType.getRole().size(); i++) {
                        RoleType role = rolesType.getRole().get(i);
                        tmpArr.add(role.getUserName());
                    }

                    Collections.sort(tmpArr, new Comparator<String>() {
                        public int compare(String d1, String d2) {
                            return java.text.Collator.getInstance().compare(d1, d2);
                        }
                    });

                    String curStr = tmpArr.get(0);
                    users.add(curStr);
                    jUserIdComboBox.addItem(curStr);
                    for (int j = 0; j < tmpArr.size(); j++) {
                        String user = tmpArr.get(j);
                        if (user.equalsIgnoreCase(curStr)) {
                            continue;
                        }
                        users.add(user);
                        jUserIdComboBox.addItem(user);
                        curStr = user;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } else {
        jUserIdComboBox.addItem(userID);
    }

}

From source file:be.fedict.eid.applet.service.signer.ooxml.OPCKeySelector.java

@Override
public KeySelectorResult select(KeyInfo keyInfo, Purpose purpose, AlgorithmMethod method,
        XMLCryptoContext context) throws KeySelectorException {
    try {/*  w  w w . j a  v a 2 s  .  com*/
        return super.select(keyInfo, purpose, method, context);
    } catch (KeySelectorException e) {
        LOG.debug("no key found via ds:KeyInfo key selector");
    }
    LOG.debug("signature resource name: " + this.signatureResourceName);
    String signatureSegment = this.signatureResourceName.substring(0,
            this.signatureResourceName.lastIndexOf("/"));
    LOG.debug("signature segment: " + signatureSegment);
    String signatureBase = this.signatureResourceName
            .substring(this.signatureResourceName.lastIndexOf("/") + 1);
    LOG.debug("signature base: " + signatureBase);
    String signatureRelationshipResourceName = signatureSegment + "/_rels/" + signatureBase + ".rels";
    LOG.debug("signature relationship resource name: " + signatureRelationshipResourceName);

    ZipArchiveInputStream zipInputStream;
    try {
        zipInputStream = new ZipArchiveInputStream(this.opcUrl.openStream(), "UTF8", true, true);
    } catch (IOException e) {
        throw new KeySelectorException(e);
    }
    ZipArchiveEntry zipEntry;
    try {
        while (null != (zipEntry = zipInputStream.getNextZipEntry())) {
            if (signatureRelationshipResourceName.equals(zipEntry.getName())) {
                break;
            }
        }
    } catch (IOException e) {
        throw new KeySelectorException(e);
    }
    if (null == zipEntry) {
        LOG.warn("relationship part not present: " + signatureRelationshipResourceName);
        throw new KeySelectorException("no key found");
    }
    LOG.debug("signature relationship part found");

    JAXBElement<CTRelationships> signatureRelationshipsElement;
    try {
        signatureRelationshipsElement = (JAXBElement<CTRelationships>) this.relationshipsUnmarshaller
                .unmarshal(zipInputStream);
    } catch (JAXBException e) {
        throw new KeySelectorException(e);
    }
    CTRelationships signatureRelationships = signatureRelationshipsElement.getValue();
    List<CTRelationship> signatureRelationshipList = signatureRelationships.getRelationship();
    List<String> certificateResourceNames = new LinkedList<String>();
    for (CTRelationship signatureRelationship : signatureRelationshipList) {
        if (DIGITAL_SIGNATURE_CERTIFICATE_REL_TYPE.equals(signatureRelationship.getType())) {
            String certificateResourceName = signatureRelationship.getTarget().substring(1);
            certificateResourceNames.add(certificateResourceName);
        }
    }

    X509Certificate endEntityCertificate = null;

    for (String certificateResourceName : certificateResourceNames) {
        try {
            zipInputStream = new ZipArchiveInputStream(this.opcUrl.openStream(), "UTF8", true, true);
        } catch (IOException e) {
            throw new KeySelectorException(e);
        }
        try {
            while (null != (zipEntry = zipInputStream.getNextZipEntry())) {
                if (certificateResourceName.equals(zipEntry.getName())) {
                    break;
                }
            }
        } catch (IOException e) {
            throw new KeySelectorException(e);
        }
        if (null == zipEntry) {
            LOG.warn("certificate part not present: " + certificateResourceName);
            continue;
        }
        X509Certificate certificate;
        try {
            certificate = (X509Certificate) this.certificateFactory.generateCertificate(zipInputStream);
        } catch (CertificateException e) {
            throw new KeySelectorException(e);
        }
        LOG.debug("certificate subject: " + certificate.getSubjectX500Principal());
        if (-1 != certificate.getBasicConstraints()) {
            LOG.debug("skipping CA certificate");
            continue;
        }
        if (null != endEntityCertificate) {
            throw new KeySelectorException("two possible end entity certificates");
        }
        endEntityCertificate = certificate;
    }
    if (null == endEntityCertificate) {
        throw new KeySelectorException("no key found");
    }
    this.certificate = endEntityCertificate;
    return this;
}

From source file:com.athena.chameleon.engine.utils.JaxbUtilsTest.java

@Test
public void webAppFilterTest() {
    String xml = this.getClass().getResource("/files/webapp/web1.xml").getFile();
    File file = new File(xml);
    InputStream is = null;// w  w w.  j  a va  2 s  .  c  o m

    try {
        is = new FileInputStream(file);
        int cnt = 0;
        byte[] buf = new byte[1024];

        System.out.println("==============================================================");
        System.out.println("*                  Original File Contents                    *");
        System.out.println("==============================================================");
        while ((cnt = is.read(buf)) != -1) {
            System.out.write(buf, 0, cnt);
        }

        Object obj = JaxbUtils.unmarshal(WebAppType.class.getPackage().getName(),
                this.getClass().getResource("/files/webapp/").getFile(), file.getName());

        WebAppType webApp = (WebAppType) ((JAXBElement<?>) obj).getValue();

        // webApp? <filter />, <filter-mapping />?  ?
        List<JAXBElement<?>> elementList = webApp.getDescriptionAndDisplayNameAndIcon();

        Object o = null;
        List<ParamValueType> paramList = null;
        String[] charSet = { "UTF-8", "UTF8" };
        boolean hasEncodingFilter = false;
        boolean hasUTF8EncodingFilter = false;
        FilterNameType filtername = null;

        for (JAXBElement<?> element : elementList) {
            o = element.getValue();

            if (o instanceof FilterType) {
                filtername = ((FilterType) o).getFilterName();

                paramList = ((FilterType) o).getInitParam();
                for (ParamValueType param : paramList) {
                    // init-param? param-name? encoding?  ?
                    if (param.getParamName().getValue().toLowerCase().equals("encoding")) {
                        hasEncodingFilter = true;

                        // param-value UTF-8? ?
                        if (ArrayUtils.contains(charSet, param.getParamValue().getValue().toUpperCase())) {
                            hasUTF8EncodingFilter = true;
                            break;
                        }
                    }
                }

                if (hasEncodingFilter) {
                    break;
                }
            }
        }

        // encoding filter  UTF-8? ?   filter ? filter-mapping  .
        if (hasEncodingFilter && !hasUTF8EncodingFilter) {
            JAXBElement<?> f = null;
            JAXBElement<?> fm = null;

            for (JAXBElement<?> element : elementList) {
                o = element.getValue();

                if (o instanceof FilterType) {
                    if (((FilterType) o).getFilterName().getValue().equals(filtername.getValue())) {
                        f = element;
                    }
                } else if (o instanceof FilterMappingType) {
                    if (((FilterMappingType) o).getFilterName().getValue().equals(filtername.getValue())) {
                        fm = element;
                    }
                }
            }

            webApp.getDescriptionAndDisplayNameAndIcon().remove(f);
            webApp.getDescriptionAndDisplayNameAndIcon().remove(fm);
        }

        if (!hasUTF8EncodingFilter) {
            // <filter> element 
            FilterType filter = new FilterType();

            FilterNameType filterName = new FilterNameType();
            filterName.setValue("UTF_EncodingFilter");
            filter.setFilterName(filterName);

            FullyQualifiedClassType filterClass = new FullyQualifiedClassType();
            filterClass.setValue("com.osc.filters.SetCharacterEncodingFilter");
            filter.setFilterClass(filterClass);

            // <init-param> element 
            ParamValueType paramValue = new ParamValueType();
            com.athena.chameleon.engine.entity.xml.webapp.v2_5.String strName = new com.athena.chameleon.engine.entity.xml.webapp.v2_5.String();
            strName.setValue("encoding");
            XsdStringType strValue = new XsdStringType();
            strValue.setValue("UTF-8");
            paramValue.setParamName(strName);
            paramValue.setParamValue(strValue);

            filter.getInitParam().add(paramValue);

            paramValue = new ParamValueType();
            strName = new com.athena.chameleon.engine.entity.xml.webapp.v2_5.String();
            strName.setValue("forceEncoding");
            strValue = new XsdStringType();
            strValue.setValue("UTF-8");
            paramValue.setParamName(strName);
            paramValue.setParamValue(strValue);

            filter.getInitParam().add(paramValue);

            // <filter-mapping> elemnet 
            FilterMappingType filterMapping = new FilterMappingType();
            com.athena.chameleon.engine.entity.xml.webapp.v2_5.UrlPatternType urlPattern = new com.athena.chameleon.engine.entity.xml.webapp.v2_5.UrlPatternType();
            urlPattern.setValue("/*");
            filterMapping.getUrlPatternOrServletName().add(urlPattern);
            filterMapping.setFilterName(filterName);

            // <web-app>? filter 
            ObjectFactory factory = new ObjectFactory();
            webApp.getDescriptionAndDisplayNameAndIcon().add(factory.createWebAppTypeFilter(filter));
            webApp.getDescriptionAndDisplayNameAndIcon()
                    .add(factory.createWebAppTypeFilterMapping(filterMapping));
        }

        String xmlData = JaxbUtils.marshal(WebAppType.class.getPackage().getName(), obj, new String[] {
                "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" });

        System.out.println("\n\n==============================================================");
        System.out.println("*                  Modified File Contents                    *");
        System.out.println("==============================================================");
        System.out.println(xmlData);
    } catch (Exception e) {
        e.printStackTrace();
        fail("Error");
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
            fail("Error");
        }
    }
}

From source file:com.evolveum.midpoint.prism.parser.JaxbDomHack.java

/**
 * This is used in a form of "fromAny" to parse elements from a JAXB getAny method to prism. 
 */// w  w w .ja  v  a  2s.c o  m
public <IV extends PrismValue, ID extends ItemDefinition, C extends Containerable> Item<IV, ID> parseRawElement(
        Object element, PrismContainerDefinition<C> definition) throws SchemaException {
    Validate.notNull(definition, "Attempt to parse raw element in a container without definition");

    QName elementName = JAXBUtil.getElementQName(element);
    ItemDefinition itemDefinition = definition.findItemDefinition(elementName);

    if (itemDefinition == null) {
        itemDefinition = locateItemDefinition(definition, elementName, element);
        if (itemDefinition == null) {
            throw new SchemaException("No definition for item " + elementName);
        }
    }

    PrismContext prismContext = definition.getPrismContext();
    Item<IV, ID> subItem;
    if (element instanceof Element) {
        // DOM Element
        DomParser domParser = prismContext.getParserDom();
        XNode xnode = domParser.parseElementContent((Element) element);
        subItem = (Item<IV, ID>) prismContext.getXnodeProcessor().parseItem(xnode, elementName, itemDefinition);
    } else if (element instanceof JAXBElement<?>) {
        // JAXB Element
        JAXBElement<?> jaxbElement = (JAXBElement<?>) element;
        Object jaxbBean = jaxbElement.getValue();
        if (itemDefinition == null) {
            throw new SchemaException("No definition for item " + elementName + " in container " + definition
                    + " (parsed from raw element)", elementName);
        }
        if (itemDefinition instanceof PrismPropertyDefinition<?>) {
            // property
            PrismProperty<?> property = ((PrismPropertyDefinition<?>) itemDefinition).instantiate();
            property.setRealValue(jaxbBean);
            subItem = (Item<IV, ID>) property;
        } else if (itemDefinition instanceof PrismContainerDefinition<?>) {
            if (jaxbBean instanceof Containerable) {
                PrismContainer<?> container = ((PrismContainerDefinition<?>) itemDefinition).instantiate();
                PrismContainerValue subValue = ((Containerable) jaxbBean).asPrismContainerValue();
                container.add(subValue);
                subItem = (Item<IV, ID>) container;
            } else {
                throw new IllegalArgumentException("Unsupported JAXB bean " + jaxbBean.getClass());
            }
        } else if (itemDefinition instanceof PrismReferenceDefinition) {
            // TODO
            if (jaxbBean instanceof Referencable) {
                PrismReference reference = ((PrismReferenceDefinition) itemDefinition).instantiate();
                PrismReferenceValue refValue = ((Referencable) jaxbBean).asReferenceValue();
                reference.merge(refValue);
                subItem = (Item<IV, ID>) reference;
            } else {
                throw new IllegalArgumentException("Unsupported JAXB bean" + jaxbBean);
            }

        } else {
            throw new IllegalArgumentException("Unsupported definition type " + itemDefinition.getClass());
        }
    } else {
        throw new IllegalArgumentException("Unsupported element type " + element.getClass());
    }
    return subItem;
}

From source file:edu.harvard.i2b2.crc.ejb.QueryManagerBean.java

private RequestMessageType getI2B2RequestType(String xmlRequest) throws Exception {

    JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil();
    JAXBElement jaxbElement = jaxbUtil.unMashallFromString(xmlRequest);

    if (jaxbElement == null) {
        throw new Exception("null value in after unmarshalling request string ");
    }// w  w  w.j a  va 2s.  c om

    RequestMessageType requestMessageType = (RequestMessageType) jaxbElement.getValue();

    return requestMessageType;
}

From source file:be.fedict.eid.dss.model.bean.ServicesManagerSingletonBean.java

@SuppressWarnings("unchecked")
private Map<String, String> loadDocumentServiceClassNames() {
    LOG.debug("getDocumentServiceClassNames");
    Map<String, String> documentServiceClassNames = new HashMap<String, String>();
    Enumeration<URL> resources;
    try {/*www.j  a v a  2  s. c  o  m*/
        resources = getResources("META-INF/eid-dss-document.xml");
    } catch (IOException e) {
        LOG.error("I/O error: " + e.getMessage(), e);
        return documentServiceClassNames;
    }
    Unmarshaller unmarshaller;
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(be.fedict.eid.dss.spi.document.ObjectFactory.class);
        unmarshaller = jaxbContext.createUnmarshaller();
    } catch (JAXBException e) {
        LOG.error("JAXB error: " + e.getMessage(), e);
        return documentServiceClassNames;
    }
    while (resources.hasMoreElements()) {
        URL resource = resources.nextElement();
        LOG.debug("resource URL: " + resource.toString());
        JAXBElement<DigitalSignatureServiceDocumentType> jaxbElement;
        try {
            jaxbElement = (JAXBElement<DigitalSignatureServiceDocumentType>) unmarshaller.unmarshal(resource);
        } catch (JAXBException e) {
            LOG.error("JAXB error: " + e.getMessage(), e);
            continue;
        }
        DigitalSignatureServiceDocumentType digitalSignatureServiceDocument = jaxbElement.getValue();
        String documentServiceClassName = digitalSignatureServiceDocument.getDocumentServiceClass();
        List<String> contentTypes = digitalSignatureServiceDocument.getContentType();
        for (String contentType : contentTypes) {
            documentServiceClassNames.put(contentType, documentServiceClassName);
        }
    }
    return documentServiceClassNames;
}

From source file:org.pepstock.jem.rest.services.GfsManager.java

/**
 * Returns a content file of a specific type
 * @param type type of file/* w  ww  . j  av a 2s. c  o m*/
 * @param request file name
 * @return content of file
 * @throws JemException if any exception occurs
 */
public String getFile(GfsRequest request) throws JemException {
    // gets the web resource
    WebResource resource = getClient().getBaseWebResource();
    // creates the returned object
    GenericType<JAXBElement<GfsOutputContent>> generic = new GenericType<JAXBElement<GfsOutputContent>>() {
    };
    try {
        // creates the complete path of REST service, setting also the output format (XML)
        JAXBElement<GfsOutputContent> jaxbContact = resource.path(GfsManagerPaths.MAIN)
                .path(GfsManagerPaths.OUTPUT_FILE_CONTENT_PATH).accept(MediaType.APPLICATION_XML)
                .post(generic, request);
        // gets the returned object
        GfsOutputContent object = jaxbContact.getValue();
        // checks if has got any exception
        // Exception must be saved as attribute of returned object
        if (object.hasException()) {
            throw new JemException(object.getExceptionMessage());
        }
        return object.getContent();
    } catch (UniformInterfaceException e) {
        LogAppl.getInstance().debug(e.getMessage(), e);
        // checks http status 
        if (e.getResponse().getStatus() != 204) {
            throw new JemException(e.getMessage(), e);
        }
        return null;
    }
}

From source file:com.evolveum.midpoint.prism.marshaller.BeanMarshaller.java

private XNode marshalHeterogeneousList(Object bean, SerializationContext ctx) throws SchemaException {
    // structurally similar to a specific path through marshalXmlTypeToMap
    Class<?> beanClass = bean.getClass();
    QName propertyName = getHeterogeneousListPropertyName(beanClass);
    Method getter = inspector.findPropertyGetter(beanClass, propertyName.getLocalPart());
    Object getterResult = getValue(bean, getter, propertyName.getLocalPart());
    if (!(getterResult instanceof Collection)) {
        throw new IllegalStateException("Heterogeneous list property " + propertyName
                + " does not contain a collection but " + MiscUtil.getObjectName(getterResult));
    }//from   w w w . ja v a  2s .  c o  m
    ListXNode xlist = new ListXNode();
    for (Object value : (Collection) getterResult) {
        if (!(value instanceof JAXBElement)) {
            throw new IllegalStateException(
                    "Heterogeneous list contains a value that is not a JAXBElement: " + value);
        }
        JAXBElement jaxbElement = (JAXBElement) value;
        Object realValue = jaxbElement.getValue();
        if (realValue == null) {
            throw new IllegalStateException("Heterogeneous list contains a null value"); // TODO
        }
        QName typeName = inspector.determineTypeForClass(realValue.getClass());
        XNode marshaled = marshallValue(realValue, typeName, false, ctx);
        marshaled.setElementName(jaxbElement.getName());
        setExplicitTypeDeclarationIfNeededForHeteroList(marshaled, realValue);
        xlist.add(marshaled);
    }
    return xlist;
}