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:edu.harvard.i2b2.crc.loader.delegate.LoaderQueryRequestDelegate.java

/**
 * @see edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate#handleRequest(java.lang.String)
 *///from  w  ww . ja v a 2 s.  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;
        try {

            SecurityType securityType = null;
            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));
            } 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:esg.node.components.registry.ShardsListGleaner.java

public synchronized ShardsListGleaner loadMyShardsWhitelist() {
    log.info("Loading my SHARDS Whitelist info from " + shardsListPath + shardsListFile);
    try {//from ww  w  .  ja  v a2s . com
        JAXBContext jc = JAXBContext.newInstance(Shards.class);
        Unmarshaller u = jc.createUnmarshaller();
        JAXBElement<Shards> root = u.unmarshal(new StreamSource(new File(shardsListPath + shardsListFile)),
                Shards.class);
        shardlist = root.getValue();
    } catch (Exception e) {
        log.error(e);
    }
    return this;
}

From source file:eu.europa.ejusticeportal.dss.controller.config.Config.java

/**
 * Refresh the repository/*from   www. j a va  2  s . c o m*/
 * 
 * @param portal the PortalFacade
 */
private void refresh(PortalFacade portal) {
    String xml = portal.getCardProfileXML();
    if (xml == null || xml.isEmpty()) {
        profiles.clear();
        specialProfiles.clear();
        cachedXml = xml;
    } else if (!xml.equals(cachedXml)) {

        try {
            synchronized (profiles) {
                profiles.clear();
                specialProfiles.clear();
                InputStream is = null;

                try {

                    JAXBElement<SigningConfigType> rep = parseXml(xml);
                    List<CardProfileType> cps = rep.getValue().getSigningContextRepository().getCardProfiles()
                            .getCardProfile();

                    for (CardProfileType cp : cps) {
                        profiles.put(cp.getATR(), cp);
                    }

                    for (String atr : profiles.keySet()) {
                        if (atr.contains(".") || atr.contains("[")) {
                            specialProfiles.put(Pattern.compile(atr), atr);
                        }
                    }
                    defaults = getDefaults(rep.getValue().getSigningContextRepository());
                    methods = getMethods(rep.getValue().getSigningMethods());
                } finally {
                    IOUtils.closeQuietly(is);
                }
                cachedXml = xml;
            }
        } catch (Exception e) {
            LOGGER.error("Error loading signing context.", e);
            throw new SigningException(e);
        }

    }
}

From source file:edu.harvard.i2b2.eclipse.plugins.pft.views.PftView.java

public String getNoteFromPDO(String xmlstr) {
    String note = null;//w  w  w.j a  v a 2  s.co m
    try {
        JAXBUtil jaxbUtil = PFTJAXBUtil.getJAXBUtil();
        JAXBElement jaxbElement = jaxbUtil.unMashallFromString(xmlstr);
        DndType dndType = (DndType) jaxbElement.getValue();

        if (dndType == null)
            log.info("dndType is null");

        PatientDataType patientDataType = (PatientDataType) new JAXBUnWrapHelper()
                .getObjectByClass(dndType.getAny(), PatientDataType.class);

        if (patientDataType == null)
            log.info("patientDataType is null");

        note = patientDataType.getObservationFactSet().get(0).getObservationFact().get(0).getObservationBlob()
                .toString();
    } catch (Exception ex) {
        ex.printStackTrace();
        log.error("Error marshalling Explorer drag text");
    }
    return note;

}

From source file:com.samples.platform.service.iss.tech.support.AppOperationEventOperation.java

/**
 * @param message/*from   w w w .ja va 2  s.  c om*/
 *            the {@link JAXBElement} containing a
 *            {@link AppOperationEventRequestType}.
 * @return the {@link JAXBElement} with a
 *         {@link AppOperationEventResponseType}.
 */
@InsightEndPoint
@ServiceActivator
public final JAXBElement<AppOperationEventResponseType> appOperationEvent(
        final JAXBElement<AppOperationEventRequestType> message) {
    this.logger.debug("+appOperationEvent");
    AppOperationEventResponseType response = this.of.createAppOperationEventResponseType();
    long start = System.currentTimeMillis();
    try {
        if (this.lockableOperations != null && message.getValue().getOperationEvent() != null) {
            LockableOperationContext context = new LockableOperationContext();
            context.put("key", "what ever value");
            OperationEventEnumType event = OperationEventEnumType.START;
            try {
                event = OperationEventEnumType.fromValue(message.getValue().getOperationEvent().getEvent());
            } catch (IllegalArgumentException e) {
                event = OperationEventEnumType.START;
            }
            /*
             * For each AppOperationEventListener out of the spring context.
             */
            OperationStateEnumType state;
            for (LockableOperation operation : this.lockableOperations) {
                /* Send the event to the operation. */
                state = operation.runOperation(message.getValue().getOperationEvent().getOperationUUID(), event,
                        context);
                if (state != null) {
                    response.setReport(new OperationStateType());
                    response.getReport().setOperationUUID(operation.getUUID());
                    response.getReport().setState(state.value());
                }
            }
        }
    } catch (Throwable e) {
        /* Add a not covered error to the response. */
        this.logger.error(e.getMessage(), e);
    } finally {
        this.logger.debug(" appOperationEvent duration {}",
                DateUtil.getDuration(start, System.currentTimeMillis()));
        this.logger.debug("-appOperationEvent #{}, #f{}", response/* .get() */ != null ? 1 : 0,
                response.getFailure().size());
    }
    return this.of.createAppOperationEventResponse(response);
}

From source file:edu.harvard.i2b2.eclipse.plugins.admin.utilities.views.PatientDataMessage.java

public PatientDataType getPatientDataType(String response) {
    PatientDataType patientData = null;//from  w ww.jav  a2s . com

    try {
        JAXBElement jaxbElement = PFTJAXBUtil.getJAXBUtil().unMashallFromString(response);
        ResponseMessageType respMessageType = (ResponseMessageType) jaxbElement.getValue();
        BodyType bodyType = respMessageType.getMessageBody();
        JAXBUnWrapHelper helper = new JAXBUnWrapHelper();
        patientData = (PatientDataType) helper.getObjectByClass(bodyType.getAny(), PatientDataType.class);
    } catch (JAXBUtilException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return patientData;
}

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

@Test
public void unmarshalVeryComplexContentExplicit() throws Exception {
    JAXBContext context = JAXBContext.newInstance("org.javelin.sws.ext.bind.context1");
    // ClassWithVeryComplexContent value = new ClassWithVeryComplexContent("test", "str", new ClassWithComplexContent("test", 42, "inside"));
    Unmarshaller um = context.createUnmarshaller();
    InputStream inputStream = new ClassPathResource("very-complex-content-01.xml", this.getClass())
            .getInputStream();/*w  w  w . j av a 2s. c  o m*/
    JAXBElement<ClassWithVeryComplexContent> je = um.unmarshal(
            XMLInputFactory.newFactory().createXMLEventReader(inputStream), ClassWithVeryComplexContent.class);
    assertTrue(je.getDeclaredType() == ClassWithVeryComplexContent.class);
    assertFalse("Should not be nil", je.isNil());
    assertTrue(je.getValue() instanceof ClassWithVeryComplexContent);
    ClassWithVeryComplexContent ob = (ClassWithVeryComplexContent) 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"));
}

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

public Shards createShardsWhitelistFromString(String shardsListContentString) {
    log.info("Loading my SHARDS info from \n" + shardsListContentString + "\n");
    Shards fromContentShardsList = null;
    try {/*from ww w. j ava 2  s . co m*/
        JAXBContext jc = JAXBContext.newInstance(Shards.class);
        Unmarshaller u = jc.createUnmarshaller();
        JAXBElement<Shards> root = u.unmarshal(new StreamSource(new StringReader(shardsListContentString)),
                Shards.class);
        fromContentShardsList = root.getValue();
    } catch (Exception e) {
        log.error(e);
    }
    return fromContentShardsList;
}

From source file:be.fedict.hsm.client.HSMProxyClient.java

/**
 * Gives back the X509 certificate chain for the given key alias.
 * //from ww  w .jav a  2  s.c o m
 * @param alias
 * @return the X509 certificate chain as a list.
 * @throws CertificateException
 */
public List<X509Certificate> getCertificateChain(String alias) throws CertificateException {
    GetCertificateChainRequest getCertificateChainRequest = this.hsmObjectFactory
            .createGetCertificateChainRequest();
    getCertificateChainRequest.setProfile(DSSConstants.HSM_PROXY_DSS_PROFILE_URI);
    String requestId = "request-" + UUID.randomUUID().toString();
    getCertificateChainRequest.setRequestID(requestId);

    {
        AnyType optionalInputs = this.dssObjectFactory.createAnyType();
        getCertificateChainRequest.setOptionalInputs(optionalInputs);
        KeySelector keySelector = this.dssObjectFactory.createKeySelector();
        optionalInputs.getAny().add(keySelector);
        KeyInfoType keyInfo = this.dsObjectFactory.createKeyInfoType();
        keySelector.setKeyInfo(keyInfo);
        keyInfo.getContent().add(this.dsObjectFactory.createKeyName(alias));
    }

    ResponseBaseType response = this.dssPort.getCertificateChain(getCertificateChainRequest);
    // TODO: error handling
    List<Object> optionalOutputContentList = response.getOptionalOutputs().getAny();
    for (Object optionalOutputContent : optionalOutputContentList) {
        LOG.debug("optional output type: " + optionalOutputContent.getClass().getName());
        if (optionalOutputContent instanceof JAXBElement) {
            JAXBElement jaxbElement = (JAXBElement) optionalOutputContent;
            KeyInfoType keyInfo = (KeyInfoType) jaxbElement.getValue();
            List<Object> keyInfoContent = keyInfo.getContent();
            JAXBElement keyInfoObject = (JAXBElement) keyInfoContent.get(0);
            LOG.debug("key info object type: " + keyInfoObject.getClass().getName());
            X509DataType x509Data = (X509DataType) keyInfoObject.getValue();
            List<Object> x509DataContent = x509Data.getX509IssuerSerialOrX509SKIOrX509SubjectName();
            List<X509Certificate> certificateChain = new LinkedList<X509Certificate>();
            for (Object x509DataObject : x509DataContent) {
                LOG.debug("x509 data object type: " + x509DataObject.getClass().getName());
                JAXBElement x509DataElement = (JAXBElement) x509DataObject;
                LOG.debug("type: " + x509DataElement.getValue().getClass().getName());
                byte[] encodedCertificate = (byte[]) x509DataElement.getValue();
                X509Certificate certificate = (X509Certificate) this.certificateFactory
                        .generateCertificate(new ByteArrayInputStream(encodedCertificate));
                certificateChain.add(certificate);
            }
            return certificateChain;
        }
    }
    return null;
}

From source file:arxiv.xml.XMLParser.java

/**
 * Parse the XML response from the arXiv OAI repository.
 *
 * @throws NullPointerException if xmlData 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
 */// ww w .j a v  a  2  s .com
public ParsedXmlResponse parse(String xmlData) {

    OAIPMHtype unmarshalledResponse;
    try {
        StringReader reader = new StringReader(xmlData);
        JAXBElement<OAIPMHtype> jaxbElement = (JAXBElement<OAIPMHtype>) unmarshaller.unmarshal(reader);

        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");
}