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:arxiv.xml.XMLParser.java

/**
 * Parse a single record of article metadata.
 * @throws ParseException if there is a parsing error
 *//*w  ww  . j a  v a  2 s  .c  o m*/
private ArticleMetadata parseRecord(RecordType xmlRecord, ZonedDateTime retrievalDateTime) {
    ArticleMetadata.ArticleMetadataBuilder articleBuilder = ArticleMetadata.builder();
    articleBuilder.retrievalDateTime(retrievalDateTime);

    HeaderType header = xmlRecord.getHeader();
    articleBuilder.identifier(normalizeSpace(header.getIdentifier()))
            .datestamp(parseDatestamp(normalizeSpace(header.getDatestamp())))
            .sets(header.getSetSpec().stream().map(StringUtils::normalizeSpace).collect(Collectors.toSet()))
            .deleted(header.getStatus() != null && header.getStatus() == StatusType.DELETED);

    @SuppressWarnings("unchecked")
    JAXBElement<ArXivRawType> jaxbElement = (JAXBElement<ArXivRawType>) xmlRecord.getMetadata().getAny();

    ArXivRawType metadata = jaxbElement.getValue();
    articleBuilder.id(normalizeSpace(metadata.getId())).submitter(normalizeSpace(metadata.getSubmitter()))
            .versions(metadata.getVersion().stream()
                    .map(versionType -> ArticleVersion.builder()
                            .versionNumber(parseVersionNumber(normalizeSpace(versionType.getVersion())))
                            .submissionTime(parseSubmissionTime(normalizeSpace(versionType.getDate())))
                            .size(normalizeSpace(versionType.getSize()))
                            .sourceType(normalizeSpace(versionType.getSourceType())).build())
                    .collect(Collectors.toSet()))
            .title(normalizeSpace(metadata.getTitle())).authors(normalizeSpace(metadata.getAuthors()))
            .categories(parseCategories(normalizeSpace(metadata.getCategories())))
            .comments(normalizeSpace(metadata.getComments())).proxy(normalizeSpace(metadata.getProxy()))
            .reportNo(normalizeSpace(metadata.getReportNo())).acmClass(normalizeSpace(metadata.getAcmClass()))
            .mscClass(normalizeSpace(metadata.getMscClass()))
            .journalRef(normalizeSpace(metadata.getJournalRef())).doi(normalizeSpace(metadata.getDoi()))
            .license(normalizeSpace(metadata.getLicense()))
            .articleAbstract(normalizeSpace(metadata.getAbstract()));

    return articleBuilder.build();
}

From source file:com.rest4j.ApiFactory.java

/**
 * Create the API instance. The XML describing the API is read, preprocessed, analyzed for errors,
 * and the internal structures for Java object marshalling and unmarshalling are created, as
 * well as endpoint mappings./*from   w  ww  .ja v  a  2 s.  com*/
 *
 * @return The API instance
 * @throws ConfigurationException When there is a problem with your XML description.
 */
public API createAPI() throws ConfigurationException {
    try {
        JAXBContext context;
        if (extObjectFactory == null)
            context = JAXBContext.newInstance(com.rest4j.impl.model.ObjectFactory.class);
        else
            context = JAXBContext.newInstance(com.rest4j.impl.model.ObjectFactory.class, extObjectFactory);
        Document xml = getDocument();

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Source apiXsdSource = new StreamSource(getClass().getResourceAsStream("api.xsd"));
        List<Source> xsds = new ArrayList<Source>();
        xsds.add(apiXsdSource);
        Schema schema;
        if (!StringUtils.isEmpty(extSchema)) {
            xsds.add(new StreamSource(getClass().getClassLoader().getResourceAsStream(extSchema)));
        }
        xsds.add(new StreamSource(getClass().getResourceAsStream("html.xsd")));
        schema = schemaFactory.newSchema(xsds.toArray(new Source[xsds.size()]));

        Unmarshaller unmarshaller = context.createUnmarshaller();
        unmarshaller.setSchema(schema);
        JAXBElement<com.rest4j.impl.model.API> element = (JAXBElement<com.rest4j.impl.model.API>) unmarshaller
                .unmarshal(xml);
        com.rest4j.impl.model.API root = element.getValue();
        APIImpl api;
        api = new APIImpl(root, pathPrefix, serviceProvider,
                factories.toArray(new ObjectFactory[factories.size()]),
                fieldFilters.toArray(new FieldFilter[fieldFilters.size()]), permissionChecker);
        return api;
    } catch (javax.xml.bind.UnmarshalException e) {
        if (e.getLinkedException() instanceof SAXParseException) {
            SAXParseException spe = (SAXParseException) e.getLinkedException();
            throw new ConfigurationException("Cannot parse " + apiDescriptionXml, spe);
        }
        throw new AssertionError(e);
    } catch (ConfigurationException e) {
        throw e;
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new AssertionError(e);
    }
}

From source file:esg.common.security.PolicyGleaner.java

public synchronized PolicyGleaner loadMyPolicy(String... filenames) {
    for (String filename : filenames) {
        log.info("Loading my policy info from " + filename);
        try {/* w w w.  j  a v a 2  s  .  co  m*/
            JAXBContext jc = JAXBContext.newInstance(Policies.class);
            Unmarshaller u = jc.createUnmarshaller();
            JAXBElement<Policies> root = u.unmarshal(new StreamSource(new File(filename)), Policies.class);
            myPolicy = root.getValue();
            int count = 0;
            for (Policy policy : myPolicy.getPolicy()) {
                policySet.add(new PolicyWrapper(policy));
                count++;
            } //dedup
            log.trace("Unmarshalled [" + myPolicy.getPolicy().size() + "] policies - Inspected [" + count
                    + "] polices - resulted in [" + policySet.size() + "] policies");
            dirty = true;
        } catch (Exception e) {
            throw new ESGFPolicyException("Unable to properly load policies from [" + filename + "]", e);
        }
    }
    return this;
}

From source file:esg.node.components.registry.AtsWhitelistGleaner.java

public synchronized AtsWhitelistGleaner loadMyAtsWhitelist() {
    log.info("Loading my ATS Whitelist info from " + atsWhitelistPath + atsWhitelistFile);
    try {//  w  w w.j  a va  2s. c  o m
        JAXBContext jc = JAXBContext.newInstance(AtsWhitelist.class);
        Unmarshaller u = jc.createUnmarshaller();
        JAXBElement<AtsWhitelist> root = u
                .unmarshal(new StreamSource(new File(atsWhitelistPath + atsWhitelistFile)), AtsWhitelist.class);
        atss = root.getValue();
    } catch (Exception e) {
        log.error(e);
    }
    return this;
}

From source file:edu.harvard.i2b2.crc.delegate.loader.LoaderQueryRequestDelegate.java

/**
 * @see edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate#handleRequest(java.lang.String)
 *///  w  w w  .j a  va  2s . c o m
public String handleRequest(String requestXml, RequestHandler requestHandler) throws I2B2Exception {
    String response = null;
    JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil();

    try {
        JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml);
        RequestMessageType requestMessageType = (RequestMessageType) jaxbElement.getValue();
        BodyType bodyType = requestMessageType.getMessageBody();

        if (bodyType == null) {
            log.error("null value in body type");
            throw new I2B2Exception("null value in body type");
        }

        // Call PM cell to validate user
        StatusType procStatus = null;
        ProjectType projectType = null;
        String projectId = null;
        SecurityType securityType = null;
        try {

            if (requestMessageType.getMessageHeader() != null) {
                if (requestMessageType.getMessageHeader().getSecurity() != null) {
                    securityType = requestMessageType.getMessageHeader().getSecurity();
                }
                projectId = requestMessageType.getMessageHeader().getProjectId();
            }
            if (securityType == null) {
                procStatus = new StatusType();
                procStatus.setType("ERROR");
                procStatus.setValue("Request message missing user/password");
                response = I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, bodyType);
                return response;
            }

            PMServiceDriver pmServiceDriver = new PMServiceDriver();
            projectType = pmServiceDriver.checkValidUser(securityType, projectId);
            if (projectType == null) {
                procStatus = new StatusType();
                procStatus.setType("ERROR");
                procStatus.setValue("Invalid user/password for the given domain");
                response = I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, bodyType);
                return response;
            }

            log.debug("project name from PM " + projectType.getName());
            log.debug("project id from PM " + projectType.getId());
            if (projectType.getRole().get(0) != null) {
                log.debug("Project role from PM " + projectType.getRole().get(0));
                this.putRoles(projectId, securityType.getUsername(), securityType.getDomain(),
                        projectType.getRole());

                Node rootNode = CacheUtil.getCache().getRoot();
                List<String> roles = (List<String>) rootNode
                        .get(securityType.getDomain() + "/" + projectId + "/" + securityType.getUsername());
                if (roles != null) {
                    System.out.println("roles size !!1 " + roles.size());
                }

            } else {
                log.warn("project role not set for user [" + securityType.getUsername() + "]");
            }

        } catch (AxisFault e) {
            procStatus = new StatusType();
            procStatus.setType("ERROR");
            procStatus.setValue("Could not connect to server");
            response = I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, bodyType);
            return response;
        } catch (I2B2Exception e) {
            procStatus = new StatusType();
            procStatus.setType("ERROR");
            procStatus.setValue("Message error connecting Project Management cell");
            response = I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, bodyType);
            return response;
        } catch (JAXBUtilException e) {
            procStatus = new StatusType();
            procStatus.setType("ERROR");
            procStatus.setValue("Message error from Project Management cell");
            response = I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, bodyType);
            return response;
        }

        JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper();

        BodyType responseBodyType = null;
        if (requestHandler instanceof PublishDataRequestHandler) {

            String irodsStorageResource = null;
            for (ParamType paramType : projectType.getParam()) {

                if (paramType.getName().equalsIgnoreCase("SRBDefaultStorageResource")) {
                    irodsStorageResource = paramType.getValue();
                    log.debug("param value for SRBDefaultStorageResource" + paramType.getValue());
                }
            }
            ((PublishDataRequestHandler) requestHandler).setIrodsDefaultStorageResource(irodsStorageResource);
        }

        responseBodyType = requestHandler.execute();

        procStatus = new StatusType();
        procStatus.setType("DONE");
        procStatus.setValue("DONE");

        response = I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, responseBodyType,
                true);

    } catch (JAXBUtilException e) {
        log.error("JAXBUtil exception", e);
        StatusType procStatus = new StatusType();
        procStatus.setType("ERROR");
        procStatus.setValue(requestXml + "\n\n" + StackTraceUtil.getStackTrace(e));
        try {
            response = I2B2MessageResponseFactory.buildResponseMessage(null, procStatus, null);
        } catch (JAXBUtilException e1) {
            e1.printStackTrace();
        }
    } catch (I2B2Exception e) {
        log.error("I2B2Exception", e);
        StatusType procStatus = new StatusType();
        procStatus.setType("ERROR");
        procStatus.setValue(StackTraceUtil.getStackTrace(e));
        try {
            response = I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, null);
        } catch (JAXBUtilException e1) {
            e1.printStackTrace();
        }
    } catch (Throwable e) {
        log.error("Throwable", e);
        StatusType procStatus = new StatusType();
        procStatus.setType("ERROR");
        procStatus.setValue(StackTraceUtil.getStackTrace(e));
        try {
            response = I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, null);
        } catch (JAXBUtilException e1) {
            e1.printStackTrace();
        }
    }
    return response;
}

From source file:com.microsoft.exchange.autodiscover.SoapAutodiscoverServiceImpl.java

private String parseGetUserSettingsResponse(GetUserSettingsResponseMessage response)
        throws SoapAutodiscoverException {
    GetUserSettingsResponse soapResponse = response.getResponse().getValue();
    UserSettings userSettings = null;//from w  w w  . j av  a2s .com
    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) {
        throw new SoapAutodiscoverException(
                "Unable to perform soap operation; try again later. Message text: " + msg.toString());
    }
    //return userSettings;
    //UserSettings userSettings = sendMessageAndExtractSingleResponse(getUserSettingsSoapMessage, GET_USER_SETTINGS_ACTION);

    //Give preference to Internal URL over External URL
    String internalUri = null;
    String externalUri = null;

    for (UserSetting userSetting : userSettings.getUserSettings()) {
        String potentialAccountServiceUrl = ((StringSetting) userSetting).getValue().getValue();
        if (EXTERNAL_EWS_SERVER.equals(userSetting.getName())) {
            externalUri = potentialAccountServiceUrl;
        }
        if (INTERNAL_EWS_SERVER.equals(userSetting.getName())) {
            internalUri = potentialAccountServiceUrl;
        }
    }
    if (internalUri == null && externalUri == null) {
        throw new ExchangeWebServicesRuntimeException("Unable to find EWS Server URI in properies "
                + EXTERNAL_EWS_SERVER + " or " + INTERNAL_EWS_SERVER + " from User's Autodiscover record");
    }
    return internalUri != null ? internalUri : externalUri;
}

From source file:be.fedict.hsm.ws.impl.DigitalSignatureServicePortImpl.java

@Override
@WebMethod(operationName = "get-certificate-chain")
@WebResult(name = "Response", targetNamespace = "urn:oasis:names:tc:dss:1.0:core:schema", partName = "GetCertificateChainResponse")
public ResponseBaseType getCertificateChain(
        @WebParam(name = "GetCertificateChainRequest", targetNamespace = "urn:be:fedict:hsm-proxy:ws:dss:profiles:hsm-proxy:1.0", partName = "GetCertificateChainRequest") GetCertificateChainRequest getCertificateChainRequest) {
    String requestId = getCertificateChainRequest.getRequestID();
    AnyType optionalInputs = getCertificateChainRequest.getOptionalInputs();
    if (null == optionalInputs) {
        LOG.error("missing dss:OptionalInputs");
        return errorResponse(ResultMajor.REQUESTER_ERROR);
    }/*from  w w w  . j a  va2s. co m*/
    List<Object> optionalInputsContent = optionalInputs.getAny();
    String alias = null;
    for (Object object : optionalInputsContent) {
        if (object instanceof KeySelector) {
            KeySelector keySelector = (KeySelector) object;
            KeyInfoType keyInfo = keySelector.getKeyInfo();
            if (null == keyInfo) {
                LOG.error("missing ds:KeyInfo");
                return errorResponse(ResultMajor.REQUESTER_ERROR);
            }
            List<Object> keyInfoContent = keyInfo.getContent();
            for (Object keyInfoObject : keyInfoContent) {
                if (keyInfoObject instanceof JAXBElement) {
                    JAXBElement jaxbElement = (JAXBElement) keyInfoObject;
                    alias = (String) jaxbElement.getValue();
                }
            }
        }
    }
    if (null == alias) {
        LOG.error("missing dss:KeySelector/ds:KeyInfo/ds:KeyName");
        return errorResponse(ResultMajor.REQUESTER_ERROR);
    }
    LOG.debug("get certificate chain for alias: " + alias);
    Certificate[] certificateChain;
    try {
        certificateChain = this.signatureService.getCertificateChain(alias);
    } catch (NoSuchAlgorithmException e) {
        LOG.error("no such algo: " + e.getMessage());
        return errorResponse(ResultMajor.REQUESTER_ERROR);
    }
    if (null == certificateChain) {
        LOG.error("no cert chain found");
        return errorResponse(ResultMajor.REQUESTER_ERROR);
    }
    ResponseBaseType response = this.objectFactory.createResponseBaseType();
    response.setRequestID(requestId);
    response.setProfile(DSSConstants.HSM_PROXY_DSS_PROFILE_URI);

    Result result = this.objectFactory.createResult();
    response.setResult(result);
    result.setResultMajor(ResultMajor.SUCCESS.getUri());

    KeyInfoType keyInfo = this.xmldsigObjectFactory.createKeyInfoType();
    AnyType optionalOutputs = this.objectFactory.createAnyType();
    optionalOutputs.getAny().add(this.xmldsigObjectFactory.createKeyInfo(keyInfo));
    response.setOptionalOutputs(optionalOutputs);

    List<Object> keyInfoContent = keyInfo.getContent();
    X509DataType x509Data = this.xmldsigObjectFactory.createX509DataType();
    keyInfoContent.add(this.xmldsigObjectFactory.createX509Data(x509Data));

    List<Object> x509DataContent = x509Data.getX509IssuerSerialOrX509SKIOrX509SubjectName();
    for (Certificate certificate : certificateChain) {
        try {
            x509DataContent
                    .add(this.xmldsigObjectFactory.createX509DataTypeX509Certificate(certificate.getEncoded()));
        } catch (CertificateEncodingException e) {
            LOG.error("certificate encoding error: " + e.getMessage());
            return errorResponse(ResultMajor.RESPONDER_ERROR);
        }
    }

    return response;
}

From source file:com.t2tierp.controller.nfe.CancelaNfe.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public Map cancelaNfe(String alias, KeyStore ks, char[] senha, String codigoUf, String ambiente,
        String chaveAcesso, String numeroProtocolo, String justificativa, String cnpj) throws Exception {
    String versaoDados = "1.00";
    String url = "";
    if (codigoUf.equals("53")) {
        if (ambiente.equals("1")) {
            url = "https://nfe.sefazvirtual.rs.gov.br/ws/recepcaoevento/recepcaoevento.asmx";
        } else if (ambiente.equals("2")) {
            url = "https://homologacao.nfe.sefazvirtual.rs.gov.br/ws/recepcaoevento/recepcaoevento.asmx";
        }// w w  w . ja  va2  s. c o  m
    }
    /* fica a cargo de cada participante definir a url que ser utiizada de acordo com o cdigo da UF
     * URLs disponveis em:
     * Homologao: http://hom.nfe.fazenda.gov.br/PORTAL/WebServices.aspx
     * Produo: http://www.nfe.fazenda.gov.br/portal/WebServices.aspx
     */

    if (url.equals("")) {
        throw new Exception("URL da sefaz no definida para o cdigo de UF = " + codigoUf);
    }

    SimpleDateFormat formatoIso = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
    String dataHoraEvento = formatoIso.format(new Date());

    String xmlCanc = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
            + "<envEvento xmlns=\"http://www.portalfiscal.inf.br/nfe\" versao=\"" + versaoDados + "\">"
            + "<idLote>1</idLote>" + "<evento versao=\"" + versaoDados + "\">" + "<infEvento Id=\"ID" + "110111"
            + chaveAcesso + "01\">" + "<cOrgao>" + codigoUf + "</cOrgao>" + "<tpAmb>" + ambiente + "</tpAmb>"
            + "<CNPJ>" + cnpj + "</CNPJ>" + "<chNFe>" + chaveAcesso + "</chNFe>" + "<dhEvento>" + dataHoraEvento
            + "</dhEvento>" + "<tpEvento>110111</tpEvento>" + "<nSeqEvento>1</nSeqEvento>" + "<verEvento>"
            + versaoDados + "</verEvento>" + "<detEvento versao=\"" + versaoDados + "\">"
            + "<descEvento>Cancelamento</descEvento>" + "<nProt>" + numeroProtocolo + "</nProt>" + "<xJust>"
            + justificativa + "</xJust>" + "</detEvento>" + "</infEvento>" + "</evento>" + "</envEvento>";

    xmlCanc = Biblioteca.assinaXML(xmlCanc, alias, ks, senha, "#ID110111" + chaveAcesso + "01", "evento",
            "infEvento", "Id");

    X509Certificate certificate = (X509Certificate) ks.getCertificate(alias);
    PrivateKey privatekey = (PrivateKey) ks.getKey(alias, senha);
    SocketFactoryDinamico socketFactory = new SocketFactoryDinamico(certificate, privatekey);
    //arquivo que contm a cadeia de certificados do servio a ser consumido
    socketFactory.setFileCacerts(this.getClass().getResourceAsStream("/br/inf/portalfiscal/nfe/jssecacerts"));

    //define o protocolo a ser utilizado na conexo
    Protocol protocol = new Protocol("https", socketFactory, 443);
    Protocol.registerProtocol("https", protocol);

    OMElement omElement = AXIOMUtil.stringToOM(xmlCanc);

    RecepcaoEventoStub.NfeDadosMsg dadosMsg = new RecepcaoEventoStub.NfeDadosMsg();
    dadosMsg.setExtraElement(omElement);

    RecepcaoEventoStub.NfeCabecMsg cabecMsg = new RecepcaoEventoStub.NfeCabecMsg();
    cabecMsg.setCUF(codigoUf);
    cabecMsg.setVersaoDados(versaoDados);

    RecepcaoEventoStub.NfeCabecMsgE cabecMsgE = new RecepcaoEventoStub.NfeCabecMsgE();
    cabecMsgE.setNfeCabecMsg(cabecMsg);

    RecepcaoEventoStub stub = new RecepcaoEventoStub(url);

    RecepcaoEventoStub.NfeRecepcaoEventoResult result = stub.nfeRecepcaoEvento(dadosMsg, cabecMsgE);

    ByteArrayInputStream in = new ByteArrayInputStream(result.getExtraElement().toString().getBytes());

    JAXBContext jc = JAXBContext.newInstance("br.inf.portalfiscal.nfe.retevento");
    Unmarshaller unmarshaller = jc.createUnmarshaller();

    JAXBElement<br.inf.portalfiscal.nfe.retevento.TRetEnvEvento> retEvento = (JAXBElement) unmarshaller
            .unmarshal(in);

    Map map = new HashMap();
    if (retEvento.getValue().getRetEvento().get(0).getInfEvento().getCStat().equals("135")) {
        map.put("nfeCancelada", true);
        xmlCanc = xmlCancelamento(retEvento.getValue(), versaoDados, codigoUf, ambiente, chaveAcesso,
                numeroProtocolo, justificativa, cnpj, dataHoraEvento);
        xmlCanc = xmlCanc.replaceAll("xmlns:ns2=\"http://www.w3.org/2000/09/xmldsig#\"", "");

        xmlCanc = Biblioteca.assinaXML(xmlCanc, alias, ks, senha, "#ID110111" + chaveAcesso + "01", "evento",
                "infEvento", "Id");
        map.put("xmlCancelamento", xmlCanc);
    } else {
        map.put("nfeCancelada", false);
    }
    map.put("motivo1", retEvento.getValue().getXMotivo());
    map.put("motivo2", retEvento.getValue().getRetEvento().get(0).getInfEvento().getXMotivo());

    return map;
}

From source file:edu.cornell.mannlib.vivo.orcid.controller.OrcidConfirmationState.java

private String getElementFromOrcidIdentifier(String elementName) {
    OrcidProfile orcidProfile = getOrcidProfile();
    if (orcidProfile == null) {
        return "";
    }//from  w  ww  .  j  a va 2  s. c o  m

    OrcidId id = orcidProfile.getOrcidIdentifier();
    if (id == null) {
        log.warn("There is no ORCID Identifier in the profile.");
        return "";
    }

    List<JAXBElement<String>> idElements = id.getContent();
    if (idElements != null) {
        for (JAXBElement<String> idElement : idElements) {
            QName name = idElement.getName();
            if (name != null && elementName.equals(name.getLocalPart())) {
                String value = idElement.getValue();
                if (value != null) {
                    return value;
                }
            }
        }
    }
    log.warn("Didn't find the element '' in the ORCID Identifier: " + idElements);
    return "";
}

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

@Test
public void unmarshalVeryComplexContentExplicitRI() 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();/*from   www  . j a  va  2 s.c  om*/
    // will throw javax.xml.bind.UnmarshalException: unexpected element (uri:"urn:test", local:"root"). Expected elements are <{y}x"
    JAXBElement<org.javelin.sws.ext.bind.jaxb.context6.ClassWithVeryComplexContent> je = um.unmarshal(
            XMLInputFactory.newFactory().createXMLEventReader(inputStream),
            org.javelin.sws.ext.bind.jaxb.context6.ClassWithVeryComplexContent.class);
    org.javelin.sws.ext.bind.jaxb.context6.ClassWithVeryComplexContent ob = je.getValue();
    assertThat(ob.getStr(), equalTo("test-1"));
    assertThat(ob.getInside(), equalTo("str"));
    assertThat(ob.getInside2().getNumber(), equalTo(42));
    assertThat(ob.getInside2().getStr(), equalTo("test-2"));
    assertThat(ob.getInside2().getInside(), equalTo("inside"));
}