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:com.evolveum.midpoint.model.impl.scripting.expressions.SearchEvaluator.java

public <T extends ObjectType> Data evaluate(final SearchExpressionType searchExpression, Data input,
        final ExecutionContext context, final OperationResult result) throws ScriptExecutionException {
    Validate.notNull(searchExpression.getType());

    boolean noFetch = expressionHelper.getArgumentAsBoolean(searchExpression.getParameter(), PARAM_NO_FETCH,
            input, context, false, "search", result);

    Class<T> objectClass = (Class) ObjectTypes.getObjectTypeFromTypeQName(searchExpression.getType())
            .getClassDefinition();// ww  w.j  a v a 2s. c  om

    ObjectQuery objectQuery = null;
    if (searchExpression.getSearchFilter() != null) {
        // todo resolve variable references in the filter
        objectQuery = new ObjectQuery();
        try {
            ObjectFilter filter = QueryConvertor.parseFilter(searchExpression.getSearchFilter(), objectClass,
                    prismContext);
            objectQuery.setFilter(filter);
        } catch (SchemaException e) {
            throw new ScriptExecutionException("Couldn't parse object filter due to schema exception", e);
        }
    }

    final String variableName = searchExpression.getVariable();

    Data oldVariableValue = null;
    if (variableName != null) {
        oldVariableValue = context.getVariable(variableName);
    }

    final Data outputData = Data.createEmpty();

    final MutableBoolean atLeastOne = new MutableBoolean(false);

    ResultHandler<T> handler = new ResultHandler<T>() {
        @Override
        public boolean handle(PrismObject<T> object, OperationResult parentResult) {
            atLeastOne.setValue(true);
            if (searchExpression.getScriptingExpression() != null) {
                if (variableName != null) {
                    context.setVariable(variableName, object);
                }
                JAXBElement<?> childExpression = searchExpression.getScriptingExpression();
                try {
                    outputData.addAllFrom(scriptingExpressionEvaluator.evaluateExpression(
                            (ScriptingExpressionType) childExpression.getValue(), Data.create(object), context,
                            result));
                    result.setSummarizeSuccesses(true);
                    result.summarize();
                } catch (ScriptExecutionException e) {
                    throw new SystemException(e); // todo think about this
                }
            } else {
                outputData.addItem(object);
            }
            return true;
        }
    };

    try {
        modelService.searchObjectsIterative(objectClass, objectQuery, handler,
                operationsHelper.createGetOptions(noFetch), context.getTask(), result);
    } catch (SchemaException | ObjectNotFoundException | SecurityViolationException | CommunicationException
            | ConfigurationException e) {
        throw new ScriptExecutionException("Couldn't execute searchObjects operation: " + e.getMessage(), e);
    }

    if (atLeastOne.isFalse()) {
        String matching;
        if (objectQuery != null) {
            matching = "matching ";
        } else {
            matching = "";
        }
        context.println(
                "Warning: no " + matching + searchExpression.getType().getLocalPart() + " object found"); // temporary hack, this will be configurable
    }

    if (variableName != null) {
        context.setVariable(variableName, oldVariableValue);
    }
    return outputData;
}

From source file:edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalPanelCellQueryItem.java

public PatientSet getPatientSetFromResponseXML(String responseXML) throws Exception {
    JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil();

    @SuppressWarnings("rawtypes")
    JAXBElement jaxbElement = jaxbUtil.unMashallFromString(responseXML);
    ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue();
    BodyType bodyType = messageType.getMessageBody();
    PatientDataResponseType responseType = (PatientDataResponseType) new JAXBUnWrapHelper()
            .getObjectByClass(bodyType.getAny(), PatientDataResponseType.class);
    PatientDataType patientDataType = responseType.getPatientData();

    PatientSet patientSet = patientDataType.getPatientSet();

    return patientSet;
}

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

public AtsWhitelist createAtsWhitelistFromString(String atsWhitelistContentString) {
    log.info("Loading my ATS Whitelist info from \n" + atsWhitelistContentString + "\n");
    AtsWhitelist fromContentAtsWhitelist = null;
    try {/*w  ww. j a v  a  2 s.co m*/
        JAXBContext jc = JAXBContext.newInstance(AtsWhitelist.class);
        Unmarshaller u = jc.createUnmarshaller();
        JAXBElement<AtsWhitelist> root = u
                .unmarshal(new StreamSource(new StringReader(atsWhitelistContentString)), AtsWhitelist.class);
        fromContentAtsWhitelist = root.getValue();
    } catch (Exception e) {
        log.error(e);
    }
    return fromContentAtsWhitelist;
}

From source file:com.samples.platform.util.AggregatorGetReferenceData.java

/**
 * Aggregate the messages./*  ww  w .j  a  v  a2  s .  co m*/
 *
 * @param messages
 *            The list of {@link GetReferenceDataResponseType} containing
 *            messages.
 * @return One Message with the content of all messages.
 */
public Message<?> aggregate(final Collection<Message<JAXBElement<GetReferenceDataResponseType>>> messages) {
    this.logger.trace("+aggregate {}", messages != null ? messages.size() : " collection of messages is null");
    JAXBElement<GetReferenceDataResponseType> response = null;
    if (messages != null) {
        for (Message<JAXBElement<GetReferenceDataResponseType>> message : messages) {
            if (response == null) {
                response = message.getPayload();
            } else {
                JAXBElement<GetReferenceDataResponseType> payload = message.getPayload();
                response.getValue().getReferenceData().addAll(payload.getValue().getReferenceData());
                response.getValue().getFailure().addAll(payload.getValue().getFailure());
            }
        }
    }
    MessageBuilder<JAXBElement<GetReferenceDataResponseType>> m = MessageBuilder.withPayload(response);
    this.logger.trace("-aggregate {}", messages != null ? messages.size() : " collection of messages is null");
    return m.build();
}

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

/**
 * Parse a single record of article metadata.
 * @throws ParseException if there is a parsing error
 *///from  w w w .j  a  v  a  2  s  .  c o m
@VisibleForTesting
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.tremolosecurity.scale.config.ScaleCommonConfig.java

@PostConstruct
public void init() {
    try {/*  w  w  w.  j a v  a  2 s.c om*/
        ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
                .getContext();

        String logPath = null;

        try {
            logPath = InitialContext.doLookup("java:comp/env/scaleLog4jPath");
        } catch (NamingException ne) {
            try {
                logPath = InitialContext.doLookup("java:/env/scaleLog4jPath");
            } catch (NamingException ne2) {
                logPath = null;
            }
        }
        if (logPath == null) {
            Properties props = new Properties();
            props.put("log4j.rootLogger", "info,console");

            //props.put("log4j.appender.console","org.apache.log4j.RollingFileAppender");
            //props.put("log4j.appender.console.File","/home/mlb/myvd.log");
            props.put("log4j.appender.console", "org.apache.log4j.ConsoleAppender");
            props.put("log4j.appender.console.layout", "org.apache.log4j.PatternLayout");
            props.put("log4j.appender.console.layout.ConversionPattern", "[%d][%t] %-5p %c{1} - %m%n");

            PropertyConfigurator.configure(props);
        } else {

            if (logPath.startsWith("WEB-INF/")) {
                org.apache.log4j.xml.DOMConfigurator.configure(context.getRealPath(logPath));
            } else {
                org.apache.log4j.xml.DOMConfigurator.configure(logPath);
            }

        }

        logger = Logger.getLogger(ScaleCommonConfig.class.getName());

        logger.info("Initializing Scale " + version);

        String configPath = null;

        try {
            configPath = InitialContext.doLookup("java:comp/env/scaleConfigPath");
        } catch (NamingException ne) {
            try {
                configPath = InitialContext.doLookup("java:/env/scaleConfigPath");
            } catch (NamingException ne2) {
                configPath = null;
            }

        }

        if (configPath == null) {
            configPath = "WEB-INF/scaleConfig.xml";
            logger.warn("No configuraiton path found - Loading configuration from '" + configPath + "'");
        } else {
            logger.info("Loading configuration from '" + configPath + "'");
        }

        InputStream in = null;

        if (configPath.startsWith("WEB-INF")) {

            in = new ByteArrayInputStream(ScaleCommonConfig
                    .includeEnvironmentVariables(context.getRealPath("/" + configPath)).getBytes("UTF-8"));

        } else {
            in = new ByteArrayInputStream(
                    ScaleCommonConfig.includeEnvironmentVariables(configPath).getBytes("UTF-8"));
        }

        JAXBContext jc = JAXBContext.newInstance("com.tremolosecurity.scale.config.xml");
        Unmarshaller unmarshaller = jc.createUnmarshaller();

        Object obj = unmarshaller.unmarshal(in);

        JAXBElement<ScaleCommonConfigType> scaleConfig = (JAXBElement<ScaleCommonConfigType>) obj;

        this.scaleConfig = scaleConfig.getValue();

        String ksPath = this.scaleConfig.getServiceConfiguration().getKeyStorePath();
        String ksPass = this.scaleConfig.getServiceConfiguration().getKeyStorePassword();

        in = null;

        if (ksPath.startsWith("WEB-INF")) {
            in = context.getResourceAsStream("/" + ksPath);
        } else {
            in = new FileInputStream(ksPath);
        }

        this.tlsKeys = KeyStore.getInstance("JKS");
        this.tlsKeys.load(in, ksPass.toCharArray());

        this.sslctx = SSLContexts.custom().loadTrustMaterial(this.tlsKeys)
                .loadKeyMaterial(this.tlsKeys, ksPass.toCharArray()).build();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

@Override
@WebMethod/*from   w w w  .j  a  v  a2s .c o m*/
@WebResult(name = "SignResponse", targetNamespace = "urn:oasis:names:tc:dss:1.0:core:schema", partName = "SignResponse")
public SignResponse sign(
        @WebParam(name = "SignRequest", targetNamespace = "urn:oasis:names:tc:dss:1.0:core:schema", partName = "SignRequest") SignRequest signRequest) {
    LOG.debug("sign");
    Principal userPrincipal = this.webServiceContext.getUserPrincipal();
    if (null != userPrincipal) {
        String userName = userPrincipal.getName();
        LOG.debug("username: " + userName);
    } else {
        LOG.debug("no user principal");
    }
    String requestId = signRequest.getRequestID();
    String digestMethodAlgorithm = null;
    byte[] digestValue = null;
    String keyAlias = null;
    InputDocuments inputDocuments = signRequest.getInputDocuments();
    if (null == inputDocuments) {
        LOG.error("missing dss:InputDocuments");
        return errorSignResponse(ResultMajor.REQUESTER_ERROR);
    }
    List<Object> inputDocumentsContent = inputDocuments.getDocumentOrTransformedDataOrDocumentHash();
    for (Object object : inputDocumentsContent) {
        if (object instanceof DocumentHash) {
            DocumentHash documentHash = (DocumentHash) object;
            DigestMethodType digestMethod = documentHash.getDigestMethod();
            digestMethodAlgorithm = digestMethod.getAlgorithm();
            digestValue = documentHash.getDigestValue();
        }
    }
    AnyType optionalInputs = signRequest.getOptionalInputs();
    if (null == optionalInputs) {
        LOG.error("missing dss:OptionalInputs");
        return errorSignResponse(ResultMajor.REQUESTER_ERROR);
    }
    List<Object> optionalInputsContent = optionalInputs.getAny();
    for (Object object : optionalInputsContent) {
        if (object instanceof KeySelector) {
            KeySelector keySelector = (KeySelector) object;
            KeyInfoType keyInfo = keySelector.getKeyInfo();
            List<Object> keyInfoContent = keyInfo.getContent();
            for (Object keyInfoObject : keyInfoContent) {
                if (keyInfoObject instanceof JAXBElement) {
                    JAXBElement jaxbElement = (JAXBElement) keyInfoObject;
                    keyAlias = (String) jaxbElement.getValue();
                }
            }
        }
    }

    if (null == digestMethodAlgorithm) {
        LOG.error("missing digest algo");
        return errorSignResponse(ResultMajor.REQUESTER_ERROR);
    }
    if (null == digestValue) {
        LOG.error("missing digest value");
        return errorSignResponse(ResultMajor.REQUESTER_ERROR);
    }
    if (null == keyAlias) {
        LOG.error("missing dss:KeySelector");
        return errorSignResponse(ResultMajor.REQUESTER_ERROR);
    }
    LOG.debug("digest algo: " + digestMethodAlgorithm);
    LOG.debug("key alias: " + keyAlias);

    byte[] signatureValue;
    try {
        signatureValue = this.signatureService.sign(digestMethodAlgorithm, digestValue, keyAlias);
    } catch (NoSuchAlgorithmException e) {
        return errorSignResponse(ResultMajor.REQUESTER_ERROR);
    }

    SignResponse signResponse = this.objectFactory.createSignResponse();
    signResponse.setRequestID(requestId);
    signResponse.setProfile(DSSConstants.HSM_PROXY_DSS_PROFILE_URI);

    Result result = this.objectFactory.createResult();
    signResponse.setResult(result);
    result.setResultMajor(ResultMajor.SUCCESS.getUri());
    result.setResultMinor(DSSConstants.RESULT_MINOR_VALID_ON_ALL_DOCS);

    SignatureObject signatureObject = this.objectFactory.createSignatureObject();
    signResponse.setSignatureObject(signatureObject);
    Base64Signature base64Signature = this.objectFactory.createBase64Signature();
    signatureObject.setBase64Signature(base64Signature);
    base64Signature.setValue(signatureValue);

    return signResponse;
}

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

@Override
public String buildGuestSessionUrl(long sessionId) {
    BlackboardBuildSessionUrl buildSessionUrlRequest = new BlackboardBuildSessionUrl();
    buildSessionUrlRequest.setSessionId(sessionId);
    buildSessionUrlRequest.setDisplayName("GUEST_PLACEHOLDER");
    final Object urlResponseObject = sasWebServiceOperations
            .marshalSendAndReceiveToSAS("http://sas.elluminate.com/BuildSessionUrl", buildSessionUrlRequest);
    @SuppressWarnings("unchecked")
    JAXBElement<BlackboardUrlResponse> jaxbResponse = (JAXBElement<BlackboardUrlResponse>) urlResponseObject;
    return jaxbResponse.getValue().getUrl().replace("&username=GUEST_PLACEHOLDER", "");
}

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

@Override
public String buildSessionUrl(long sessionId, ConferenceUser user) {
    BlackboardBuildSessionUrl buildSessionUrlRequest = new BlackboardBuildSessionUrl();
    buildSessionUrlRequest.setSessionId(sessionId);
    buildSessionUrlRequest.setDisplayName(user.getDisplayName());
    buildSessionUrlRequest.setUserId(user.getBlackboardUniqueId());
    final Object urlResponseObject = sasWebServiceOperations
            .marshalSendAndReceiveToSAS("http://sas.elluminate.com/BuildSessionUrl", buildSessionUrlRequest);
    @SuppressWarnings("unchecked")
    JAXBElement<BlackboardUrlResponse> jaxbResponse = (JAXBElement<BlackboardUrlResponse>) urlResponseObject;
    return jaxbResponse.getValue().getUrl();
}

From source file:org.wallerlab.yoink.molecular.service.translator.MolecularSystemTranslator.java

private void loopOverAtoms(List<Atom> atoms, AtomArray cmlAtomArray) {
    for (Object elementAtom : cmlAtomArray.getAnyCmlOrAnyOrAny()) {
        @SuppressWarnings("unchecked")
        JAXBElement<org.xml_cml.schema.Atom> element = (JAXBElement<org.xml_cml.schema.Atom>) elementAtom;
        if (element.getDeclaredType() == org.xml_cml.schema.Atom.class) {
            org.xml_cml.schema.Atom cmlAtom = (org.xml_cml.schema.Atom) element.getValue();
            parseAtom(atoms, cmlAtom);/*from ww  w.  j av a2 s  .  co m*/
        }
    }
}