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:eu.domibus.ebms3.receiver.MSHWebservice.java

private Messaging getMessaging(SOAPMessage request) throws SOAPException, JAXBException {
    Node messagingXml = (Node) request.getSOAPHeader().getChildElements(ObjectFactory._Messaging_QNAME).next();
    Unmarshaller unmarshaller = this.jaxbContext.createUnmarshaller(); //Those are not thread-safe, therefore a new one is created each call
    @SuppressWarnings("unchecked")
    JAXBElement<Messaging> root = (JAXBElement<Messaging>) unmarshaller.unmarshal(messagingXml);
    return root.getValue();
}

From source file:edu.harvard.i2b2.eclipse.login.LoginHelper.java

public void setUserInfo(String responseXML) throws Exception {
    log.info("PM response message: /n" + responseXML);
    UserInfoBean.pmResponse(responseXML);

    JAXBUtil jaxbUtil = new JAXBUtil(new String[] { "edu.harvard.i2b2.pm.datavo.pm", //$NON-NLS-1$
            "edu.harvard.i2b2.pm.datavo.i2b2message" //$NON-NLS-1$
    });/*from  w ww  .j ava 2 s .  com*/
    JAXBElement jaxbElement = jaxbUtil.unMashallFromString(responseXML);
    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();
        ConfigureType response = (ConfigureType) helper.getObjectByClass(bodyType.getAny(),
                ConfigureType.class);

        userInfoBean.setEnvironment(response.getEnvironment());
        userInfoBean.setUserName(response.getUser().getUserName());
        userInfoBean.setUserFullName(response.getUser().getFullName());
        userInfoBean.setUserPassword(response.getUser().getPassword());
        userInfoBean.setUserKey(response.getUser().getKey());
        userInfoBean.setUserDomain(response.getUser().getDomain());
        userInfoBean.setHelpURL(response.getHelpURL());
        userInfoBean.isAdmin(response.getUser().isIsAdmin());

        //Save Global variables in properties
        if (response.getGlobalData() != null) {
            for (ParamType param : response.getGlobalData().getParam())
                userInfoBean.setGlobals(param.getName(), param.getValue());
        }
        //Save projects         
        if (response.getUser().getProject() != null)
            userInfoBean.setProjects(response.getUser().getProject());

        //Save Cell
        if (response.getCellDatas() != null)
            userInfoBean.setCellDatas(response.getCellDatas());
    }
}

From source file:com.catify.processengine.core.nodes.eventdefinition.EventDefinitionFactory.java

/**
 * Gets all actor references of the process (including sub processes).
 *
 * @param clientId the client id/*from ww w.j a  v  a2s. co  m*/
 * @param processJaxb the process jaxb
 * @param subProcessesJaxb the sub processes jaxb
 * @param flowNodeJaxb the flow node jaxb
 * @return the all actor references
 */
private Set<ActorRef> getTopLevelActorReferences(String clientId, TProcess processJaxb) {
    Set<ActorRef> actorReferences = new HashSet<ActorRef>();

    List<JAXBElement<? extends TFlowElement>> flowElements = new ArrayList<JAXBElement<? extends TFlowElement>>();

    flowElements = processJaxb.getFlowElement();

    for (JAXBElement<? extends TFlowElement> flowElement : flowElements) {
        if (flowElement.getValue() instanceof TFlowNode) {
            actorReferences.add(new ActorReferenceService().getActorReference(IdService
                    .getUniqueFlowNodeId(clientId, processJaxb, null, (TFlowNode) flowElement.getValue())));
        }
    }

    return actorReferences;
}

From source file:ddf.security.pdp.realm.xacml.processor.BalanaClient.java

/**
 * Unmarshalls the XACML response.//  w  w w  .j a va2  s.  com
 *
 * @param xacmlResponse The XACML response with all namespaces and namespace prefixes added.
 * @return The XACML response.
 * @throws PdpException
 */
@SuppressWarnings("unchecked")
private ResponseType unmarshal(DOMResult xacmlResponse) throws PdpException {
    List<String> ctxPath = ImmutableList.of(ResponseType.class.getPackage().getName());

    if (null == parser) {
        throw new IllegalStateException("XMLParser must be configured.");
    }

    ParserConfigurator configurator = parser.configureParser(ctxPath, BalanaClient.class.getClassLoader());

    try {
        JAXBElement<ResponseType> xacmlResponseTypeElement = parser.unmarshal(configurator, JAXBElement.class,
                xacmlResponse.getNode());
        return xacmlResponseTypeElement.getValue();

    } catch (ParserException e) {
        String message = "Unable to unmarshal XACML response.";
        LOGGER.error(message);
        throw new PdpException(message, e);
    }
}

From source file:ddf.security.pdp.realm.xacml.processor.XacmlClient.java

/**
 * Unmarshalls the XACML response./* w  w  w .  j a  v  a2 s .  c o  m*/
 *
 * @param xacmlResponse The XACML response with all namespaces and namespace prefixes added.
 * @return The XACML response.
 * @throws PdpException
 */
@SuppressWarnings("unchecked")
private ResponseType unmarshal(DOMResult xacmlResponse) throws PdpException {
    List<String> ctxPath = ImmutableList.of(ResponseType.class.getPackage().getName());

    if (null == parser) {
        throw new IllegalStateException("XMLParser must be configured.");
    }

    ParserConfigurator configurator = parser.configureParser(ctxPath, XacmlClient.class.getClassLoader());

    try {
        JAXBElement<ResponseType> xacmlResponseTypeElement = parser.unmarshal(configurator, JAXBElement.class,
                xacmlResponse.getNode());
        return xacmlResponseTypeElement.getValue();

    } catch (ParserException e) {
        String message = "Unable to unmarshal XACML response.";
        LOGGER.error(message);
        throw new PdpException(message, e);
    }
}

From source file:io.github.mikesaelim.arxivoaiharvester.xml.XMLParser.java

/**
 * Parse the XML response from the arXiv OAI repository.
 *
 * @throws NullPointerException if xmlResponse is null
 * @throws ParseException if parsing fails
 * @throws RepositoryError if the repository's response was parseable but invalid
 * @throws BadArgumentException if the repository's response contains a BadArgument error
 * @throws BadResumptionTokenException if the repository's response contains a BadResumptionToken error
 */// w  ww . j  ava 2s .  co  m
public ParsedXmlResponse parse(@NonNull InputStream xmlResponse) {

    OAIPMHtype unmarshalledResponse;
    try {
        @SuppressWarnings("unchecked")
        JAXBElement<OAIPMHtype> jaxbElement = (JAXBElement<OAIPMHtype>) unmarshaller.unmarshal(xmlResponse);

        unmarshalledResponse = jaxbElement.getValue();
    } catch (Exception e) {
        throw new ParseException("Error unmarshalling XML response from repository", e);
    }

    ZonedDateTime responseDate = parseResponseDate(unmarshalledResponse.getResponseDate());

    // Parse any errors returned by the repository
    List<OAIPMHerrorType> errors = Lists.newArrayList(unmarshalledResponse.getError());
    if (!errors.isEmpty()) {
        errors.sort(repositoryErrorSeverityComparator);

        // ID_DOES_NOT_EXIST and NO_RECORDS_MATCH are not considered errors, and simply result in an empty result set
        if (errors.get(0).getCode() == OAIPMHerrorcodeType.ID_DOES_NOT_EXIST
                || errors.get(0).getCode() == OAIPMHerrorcodeType.NO_RECORDS_MATCH) {
            return ParsedXmlResponse.builder().responseDate(responseDate).records(Lists.newArrayList()).build();
        }

        // Produce error report
        StringBuilder errorStringBuilder = new StringBuilder("Received error from repository: \n");
        errors.stream().forEach(error -> errorStringBuilder.append(error.getCode().value()).append(" : ")
                .append(normalizeSpace(error.getValue())).append("\n"));
        String errorString = errorStringBuilder.toString();

        // Throw an exception corresponding to the most severe error
        switch (errors.get(0).getCode()) {
        case BAD_ARGUMENT:
            throw new BadArgumentException(errorString);
        case BAD_RESUMPTION_TOKEN:
            throw new BadResumptionTokenException(errorString);
        case BAD_VERB:
        case CANNOT_DISSEMINATE_FORMAT:
        case NO_METADATA_FORMATS:
        case NO_SET_HIERARCHY:
        default:
            throw new RepositoryError(errorString);
        }
    }

    // Handle the GetRecord response
    if (unmarshalledResponse.getGetRecord() != null) {
        ArticleMetadata record = parseRecord(unmarshalledResponse.getGetRecord().getRecord(), responseDate);

        return ParsedXmlResponse.builder().responseDate(responseDate).records(Lists.newArrayList(record))
                .build();
    }

    // Handle the ListRecords response
    if (unmarshalledResponse.getListRecords() != null) {
        ParsedXmlResponse.ParsedXmlResponseBuilder responseBuilder = ParsedXmlResponse.builder()
                .responseDate(responseDate).records(unmarshalledResponse.getListRecords().getRecord().stream()
                        .map(xmlRecord -> parseRecord(xmlRecord, responseDate)).collect(Collectors.toList()));

        ResumptionTokenType resumptionToken = unmarshalledResponse.getListRecords().getResumptionToken();
        if (resumptionToken != null) {
            responseBuilder.resumptionToken(normalizeSpace(resumptionToken.getValue()))
                    .cursor(resumptionToken.getCursor())
                    .completeListSize(resumptionToken.getCompleteListSize());
        }

        return responseBuilder.build();
    }

    // Handling of other response types is undefined
    throw new RepositoryError("Response from repository was not an error, GetRecord, or ListRecords response");
}

From source file:org.jasig.portlet.blackboardvcportlet.dao.ws.impl.MultimediaWSDaoImpl.java

@Override
public List<BlackboardMultimediaResponse> getSessionMultimedias(long bbSessionId) {
    BlackboardListSessionContent request = new ObjectFactory().createBlackboardListSessionContent();
    request.setSessionId(bbSessionId);/* w  w w . j  ava 2 s. c o m*/

    JAXBElement<BlackboardListSessionContent> createListSessionMultimedia = new ObjectFactory()
            .createListSessionMultimedia(request);
    @SuppressWarnings("unchecked")
    final JAXBElement<BlackboardMultimediaResponseCollection> objSessionResponse = (JAXBElement<BlackboardMultimediaResponseCollection>) sasWebServiceOperations
            .marshalSendAndReceiveToSAS("http://sas.elluminate.com/ListSessionMultimedia",
                    createListSessionMultimedia);

    return objSessionResponse.getValue().getMultimediaResponses();
}

From source file:core.nipr.NiprClient.java

private void processJuriductionReport(Map<String, Integer> aInPersonNumberByKey,
        LicensingReportProcessResult.LicensingReport.JurisdictionReport lJdReport,
        XMLGregorianCalendar aInCalDate, Map<String, LicenseInternal> aInOutAllLicenses) {

    LicensingReportProcessResult.LicensingReport.JurisdictionReport.PersonReferences lPReferences = lJdReport
            .getPersonReferences();//from w ww  .  j  av a  2s .  c o m
    String lPersonRef = lPReferences.getPersonReference();

    if (!aInPersonNumberByKey.containsKey(lPersonRef)) {
        System.out.println("Person: " + lPersonRef + " Not found in map");
        return;
    }

    Integer lNpnNumber = aInPersonNumberByKey.get(lPersonRef);
    List<LicensingReportProcessResult.LicensingReport.JurisdictionReport.JurisdictionReportItem> lJdReportItems = lJdReport
            .getJurisdictionReportItem();
    for (LicensingReportProcessResult.LicensingReport.JurisdictionReport.JurisdictionReportItem lJdReportItem : lJdReportItems) {
        String lState = lJdReportItem.getStateOrProvinceCode();
        LicensingReportProcessResult.LicensingReport.JurisdictionReport.JurisdictionReportItem.Licensee lLicensee = lJdReportItem
                .getLicensee();

        if (lLicensee == null) {
            System.out.println("Person: " + lPersonRef + " JurisdictionReportItem.Licensee is null");
            continue;
        }

        List<LicensingReportProcessResult.LicensingReport.JurisdictionReport.JurisdictionReportItem.Licensee.InsuranceLicense> lInsuranceLicenses = lLicensee
                .getInsuranceLicense();
        for (LicensingReportProcessResult.LicensingReport.JurisdictionReport.JurisdictionReportItem.Licensee.InsuranceLicense lInsuranceLicense : lInsuranceLicenses) {
            String lTypeCode = lInsuranceLicense.getTypeCode();

            if (!Objects.equals(lTypeCode, new String("Producer"))) {
                continue;
            }
            LicensingReportProcessResult.LicensingReport.JurisdictionReport.JurisdictionReportItem.Licensee.InsuranceLicense.License lLicense = lInsuranceLicense
                    .getLicense();
            if (lLicense == null) {
                continue;
            }

            //System.out.println("Person " + lPersonRef + " Issued License on " + lLicense.getIssueDate());
            LicenseInternal lLicenseInt = new LicenseInternal();
            lLicenseInt.licenseNumber = lLicense.getLicenseNumberId();
            XMLGregorianCalendar lCal = lLicense.getIssueDate();
            lLicenseInt.effectiveDate = CalenderUtils.toSFDCDateFormat(lCal);
            LicensingReportProcessResult.LicensingReport.JurisdictionReport.JurisdictionReportItem.Licensee.InsuranceLicense.License.LicensePeriod lPeriod = lLicense
                    .getLicensePeriod();
            if (lPeriod != null) {
                List<Serializable> lContents = lPeriod.getContent();
                for (Serializable lContent : lContents) {
                    if (lContent instanceof JAXBElement) {
                        JAXBElement lElem = (JAXBElement) lContent;
                        if (lElem.getValue() instanceof XMLGregorianCalendar) {
                            lCal = (XMLGregorianCalendar) lElem.getValue();
                            lLicenseInt.expirationDate = CalenderUtils.toSFDCDateFormat(lCal);
                        }

                    }
                }
            }
            lLicenseInt.className = lLicense.getLicenseClassDescription();
            lLicenseInt.npnNumber = Integer.toString(lNpnNumber);
            if (Objects.equals(lInsuranceLicense.getResidentLicenseIndicator(), new String("true"))) {
                lLicenseInt.isResidentLicense = true;
            }
            lLicenseInt.state = lJdReportItem.getStateOrProvinceCode();
            List<LicensingReportProcessResult.LicensingReport.JurisdictionReport.JurisdictionReportItem.Licensee.InsuranceLicense.LineOfAuthority> lLoas = lInsuranceLicense
                    .getLineOfAuthority();
            boolean oneActiveLoa = false;
            for (LicensingReportProcessResult.LicensingReport.JurisdictionReport.JurisdictionReportItem.Licensee.InsuranceLicense.LineOfAuthority l : lLoas) {
                LineOfAuthorityInternal lLoaInternal = new LineOfAuthorityInternal();
                lLoaInternal.name = l.getLineOfAuthorityDescription();
                if (Objects.equals(l.getStatusCode().toLowerCase(), new String("active"))) {
                    lLoaInternal.isActive = true;
                    oneActiveLoa = true;
                }
                lLicenseInt.linesOfAuthority.add(lLoaInternal);
            }

            if (!CalenderUtils.isNullOrWhiteSpace(lLicense.getStatusCode())) {
                if (Objects.equals(lLicense.getStatusCode().toLowerCase(), new String("active"))) {
                    lLicenseInt.isActive = true;
                }
            } else {
                lLicenseInt.isActive = oneActiveLoa;
            }
            lLicenseInt.niprUpdateDate = CalenderUtils.toSFDCDateFormat(aInCalDate);
            if (!aInOutAllLicenses.containsKey(lLicenseInt.GetKey())) {
                aInOutAllLicenses.put(lLicenseInt.GetKey(), lLicenseInt);
            }
        }
    }
}

From source file:nz.co.senanque.base.ObjectTest.java

@SuppressWarnings("unused")
@Test//from w ww . ja v a 2  s  . c  o m
public void test1() throws Exception {
    ValidationSession validationSession = m_validationEngine.createSession();

    // create a customer
    Customer customer = m_customerDAO.createCustomer();
    validationSession.bind(customer);
    Invoice invoice = new Invoice();
    invoice.setDescription("test invoice");
    customer.getInvoices().add(invoice);
    boolean exceptionFound = false;
    try {
        customer.setName("ttt");
    } catch (ValidationException e) {
        exceptionFound = true;
    }
    assertTrue(exceptionFound);

    final ObjectMetadata customerMetadata = validationSession.getMetadata(customer);
    final FieldMetadata customerTypeMetadata = customerMetadata.getFieldMetadata(Customer.CUSTOMERTYPE);

    assertFalse(customerTypeMetadata.isActive());
    assertFalse(customerTypeMetadata.isReadOnly());
    assertFalse(customerTypeMetadata.isRequired());

    customer.setName("aaaab");
    assertTrue(customerTypeMetadata.isActive());
    assertTrue(customerTypeMetadata.isReadOnly());
    assertTrue(customerTypeMetadata.isRequired());
    exceptionFound = false;
    try {
        customer.setCustomerType("B");
    } catch (Exception e) {
        exceptionFound = true;
    }
    assertTrue(exceptionFound);
    exceptionFound = false;
    try {
        customer.setCustomerType("XXX");
    } catch (Exception e) {
        exceptionFound = true;
    }
    assertTrue(exceptionFound);
    customer.setBusiness(IndustryType.AG);
    customer.setAmount(new Double(500.99));
    final long id = m_customerDAO.save(customer);
    log.info(id);

    // fetch customer back
    customer = m_customerDAO.getCustomer(id);
    final int invoiceCount = customer.getInvoices().size();
    validationSession.bind(customer);
    invoice = new Invoice();
    invoice.setDescription("test invoice2");
    customer.getInvoices().add(invoice);
    m_customerDAO.save(customer);

    // fetch customer again
    customer = m_customerDAO.getCustomer(id);
    customer.toString();
    validationSession.bind(customer);
    final Invoice inv = customer.getInvoices().get(0);
    customer.getInvoices().remove(inv);

    //ObjectMetadata metadata = validationSession.getMetadata(customer);
    ObjectMetadata metadata = customer.getMetadata();
    org.junit.Assert.assertEquals("this is a description",
            metadata.getFieldMetadata(Customer.NAME).getDescription());
    List<ChoiceBase> choices = metadata.getFieldMetadata(Customer.BUSINESS).getChoiceList();
    assertEquals(1, choices.size());
    List<ChoiceBase> choices2 = metadata.getFieldMetadata(Customer.CUSTOMERTYPE).getChoiceList();
    assertEquals(2, choices2.size());
    choices2 = metadata.getFieldMetadata(Customer.CUSTOMERTYPE).getChoiceList();
    assertEquals(2, choices2.size());

    customer.setName("aab");
    choices2 = metadata.getFieldMetadata(Customer.CUSTOMERTYPE).getChoiceList();
    assertEquals(6, choices2.size());

    // Convert customer to XML
    QName qname = new QName("http://www.example.org/sandbox", "Session");
    JAXBElement<Session> sessionJAXB = new JAXBElement<Session>(qname, Session.class, new Session());
    sessionJAXB.getValue().getCustomers().add(customer); //??This fails to actually add
    StringWriter marshallWriter = new StringWriter();
    Result marshallResult = new StreamResult(marshallWriter);
    m_marshaller.marshal(sessionJAXB, marshallResult);
    marshallWriter.flush();
    String result = marshallWriter.getBuffer().toString().trim();
    String xml = result.replaceAll("\\Qhttp://www.example.org/sandbox\\E", "http://www.example.org/sandbox");
    log.info(xml);

    // Convert customer back to objects
    SAXBuilder builder = new SAXBuilder();
    org.jdom.Document resultDOM = builder.build(new StringReader(xml));
    @SuppressWarnings("unchecked")
    JAXBElement<Session> request = (JAXBElement<Session>) m_unmarshaller.unmarshal(new JDOMSource(resultDOM));
    validationSession = m_validationEngine.createSession();
    validationSession.bind(request.getValue());
    assertEquals(3, validationSession.getProxyCount());
    List<Customer> customers = request.getValue().getCustomers();
    assertEquals(1, customers.size());
    customers.clear();
    assertEquals(1, validationSession.getProxyCount());
    request.toString();
    validationSession.close();
}

From source file:org.jasig.portlet.emailpreview.dao.exchange.ExchangeAutoDiscoverDaoImpl.java

private UserSettings sendMessageAndExtractSingleResponse(GetUserSettingsRequestMessage soapRequest,
        String soapAction, MailStoreConfiguration config) {
    GetUserSettingsResponseMessage soapResponseMessage = (GetUserSettingsResponseMessage) sendSoapRequest(
            soapRequest, soapAction, config);
    GetUserSettingsResponse soapResponse = soapResponseMessage.getResponse().getValue();

    UserSettings userSettings = null;/*from  w w  w .  j  av  a2  s .  c  om*/
    boolean warning = false;
    boolean error = false;
    StringBuilder msg = new StringBuilder();
    if (!ErrorCode.NO_ERROR.equals(soapResponse.getErrorCode())) {
        error = true;
        msg.append("Error: ").append(soapResponse.getErrorCode().value()).append(": ")
                .append(soapResponse.getErrorMessage().getValue()).append("\n");
    } else {
        JAXBElement<ArrayOfUserResponse> JAXBresponseArray = soapResponse.getUserResponses();
        ArrayOfUserResponse responseArray = JAXBresponseArray != null ? JAXBresponseArray.getValue() : null;
        List<UserResponse> responses = responseArray != null ? responseArray.getUserResponses()
                : new ArrayList<UserResponse>();
        if (responses.size() == 0) {
            error = true;
            msg.append("Error: Autodiscovery returned no Exchange mail server for mailbox");
        } else if (responses.size() > 1) {
            warning = true;
            msg.append("Warning: Autodiscovery returned multiple responses for Exchange server mailbox query");
        } else {
            UserResponse userResponse = responses.get(0);
            if (!ErrorCode.NO_ERROR.equals(userResponse.getErrorCode())) {
                error = true;
                msg.append("Received error message obtaining user mailbox's server. Error "
                        + userResponse.getErrorCode().value() + ": "
                        + userResponse.getErrorMessage().getValue());
            }
            userSettings = userResponse.getUserSettings().getValue();
        }
    }
    if (warning || error) {
        StringBuilder errorMessage = new StringBuilder("Unexpected response from soap action: " + soapAction
                + ".\nSoap Request: " + soapRequest.toString() + "\n");
        errorMessage.append(msg);
        if (error) {
            throw new EmailPreviewException("Error performing Exchange web service action " + soapAction
                    + ". Error code is " + errorMessage.toString());
        }
        log.warn("Received warning response to soap request " + soapAction + ". Error text is:\n"
                + errorMessage.toString());
        throw new EmailPreviewException("Unable to perform " + soapAction
                + " operation; try again later. Message text: " + errorMessage.toString());
    }
    return userSettings;
}