Example usage for javax.xml.bind JAXBElement getValue

List of usage examples for javax.xml.bind JAXBElement getValue

Introduction

In this page you can find the example usage for javax.xml.bind JAXBElement getValue.

Prototype

public T getValue() 

Source Link

Document

Return the content model and attribute values for this element.

See #isNil() for a description of a property constraint when this value is null

Usage

From source file:be.fedict.eid.tsl.Tsl2PdfExporter.java

private void printExtension(ExtensionType extension, Document document) throws DocumentException {

    List<Object> contentList = extension.getContent();
    for (Object content : contentList) {
        LOG.debug("extension content: " + content.getClass().getName());
        if (content instanceof JAXBElement<?>) {
            JAXBElement<?> element = (JAXBElement<?>) content;
            LOG.debug("QName: " + element.getName());
            if (true == ADDITIONAL_SERVICE_INFORMATION_QNAME.equals(element.getName())) {
                addTitle("Extension (critical: " + extension.isCritical() + ")", title3Font,
                        Paragraph.ALIGN_LEFT, 0, 0, document);
                addTitle("Additional service information", title4Font, Paragraph.ALIGN_LEFT, 0, 0, document);
                AdditionalServiceInformationType additionalServiceInformation = (AdditionalServiceInformationType) element
                        .getValue();/*w w w  .  ja va2  s.  co m*/
                LOG.debug("information value: " + additionalServiceInformation.getInformationValue());
                NonEmptyMultiLangURIType multiLangUri = additionalServiceInformation.getURI();
                LOG.debug("URI : " + multiLangUri.getValue() + " (language: " + multiLangUri.getLang() + ")");
                document.add(new Paragraph(
                        multiLangUri.getValue().substring(
                                multiLangUri.getValue().indexOf("SvcInfoExt/") + "SvcInfoExt/".length()),
                        this.valueFont));
            } else {
                addTitle("Extension (critical: " + extension.isCritical() + ")", title3Font,
                        Paragraph.ALIGN_LEFT, 0, 0, document);
                addTitle("Qualifications", title4Font, Paragraph.ALIGN_LEFT, 0, 0, document);

                LOG.debug("element namespace: " + element.getName());
                LOG.debug("element name: " + element.getScope());
                if ("http://uri.etsi.org/TrstSvc/SvcInfoExt/eSigDir-1999-93-EC-TrustedList/#"
                        .equals(element.getName().getNamespaceURI())
                        && "Qualifications".equals(element.getName().getLocalPart())) {
                    QualificationsType qualifications = (QualificationsType) element.getValue();
                    List<QualificationElementType> qualificationElements = qualifications
                            .getQualificationElement();
                    for (QualificationElementType qualificationElement : qualificationElements) {
                        QualifiersType qualifiers = qualificationElement.getQualifiers();
                        List<QualifierType> qualifierList = qualifiers.getQualifier();
                        for (QualifierType qualifier : qualifierList) {
                            document.add(new Paragraph(
                                    "Qualifier: " + qualifier.getUri().substring(
                                            qualifier.getUri().indexOf("SvcInfoExt/") + "SvcInfoExt/".length()),
                                    this.valueFont));
                        }

                        CriteriaListType criteriaList = qualificationElement.getCriteriaList();
                        String description = criteriaList.getDescription();
                        if (null != description) {
                            document.add(new Paragraph("Criterial List Description", this.labelFont));
                            document.add(new Paragraph(description, this.valueFont));
                        }
                        document.add(new Paragraph("Assert: " + criteriaList.getAssert(), this.valueFont));
                        List<PoliciesListType> policySet = criteriaList.getPolicySet();
                        for (PoliciesListType policiesList : policySet) {
                            List<ObjectIdentifierType> oids = policiesList.getPolicyIdentifier();
                            for (ObjectIdentifierType oid : oids) {
                                document.add(new Paragraph("Policy OID: " + oid.getIdentifier().getValue(),
                                        this.valueFont));
                            }
                        }
                    }
                }

            }

        } else if (content instanceof Element) {
            addTitle("Qualifications", title4Font, Paragraph.ALIGN_LEFT, 0, 0, document);
            Element element = (Element) content;
            LOG.debug("element namespace: " + element.getNamespaceURI());
            LOG.debug("element name: " + element.getLocalName());
            if ("http://uri.etsi.org/TrstSvc/SvcInfoExt/eSigDir-1999-93-EC-TrustedList/#"
                    .equals(element.getNamespaceURI()) && "Qualifications".equals(element.getLocalName())) {
                try {
                    QualificationsType qualifications = unmarshallQualifications(element);
                    List<QualificationElementType> qualificationElements = qualifications
                            .getQualificationElement();
                    for (QualificationElementType qualificationElement : qualificationElements) {
                        QualifiersType qualifiers = qualificationElement.getQualifiers();
                        List<QualifierType> qualifierList = qualifiers.getQualifier();
                        for (QualifierType qualifier : qualifierList) {
                            document.add(new Paragraph(
                                    "Qualifier: " + qualifier.getUri().substring(
                                            qualifier.getUri().indexOf("SvcInfoExt/") + "SvcInfoExt/".length()),
                                    this.valueFont));
                        }

                        CriteriaListType criteriaList = qualificationElement.getCriteriaList();
                        String description = criteriaList.getDescription();
                        if (null != description) {
                            document.add(new Paragraph("Criterial List Description", this.labelFont));
                            document.add(new Paragraph(description, this.valueFont));
                        }
                        document.add(new Paragraph("Assert: " + criteriaList.getAssert(), this.valueFont));
                        List<PoliciesListType> policySet = criteriaList.getPolicySet();
                        for (PoliciesListType policiesList : policySet) {
                            List<ObjectIdentifierType> oids = policiesList.getPolicyIdentifier();
                            for (ObjectIdentifierType oid : oids) {
                                document.add(new Paragraph("Policy OID: " + oid.getIdentifier().getValue(),
                                        this.valueFont));
                            }
                        }
                    }
                } catch (JAXBException e) {
                    LOG.error("JAXB error: " + e.getMessage(), e);
                }
            }
        }
    }
}

From source file:edu.harvard.i2b2.previousquery.QueryPreviousRunsPanel.java

private void populateChildNodes(DefaultMutableTreeNode node) {
    if (node.getUserObject().getClass().getSimpleName().equalsIgnoreCase("QueryMasterData")) {
        QueryMasterData data = (QueryMasterData) node.getUserObject();
        try {/*  www .  j  ava2 s .c om*/
            String xmlRequest = data.writeContentQueryXML();
            lastRequestMessage = xmlRequest;
            //System.out.println(xmlRequest);
            String xmlResponse = QueryListNamesClient.sendQueryRequestREST(xmlRequest);
            if (xmlResponse.equalsIgnoreCase("CellDown")) {
                final JPanel parent = this;
                java.awt.EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        JOptionPane.showMessageDialog(parent,
                                "Trouble with connection to the remote server, "
                                        + "this is often a network error, please try again",
                                "Network Error", JOptionPane.INFORMATION_MESSAGE);
                    }
                });
                return;
            }
            lastResponseMessage = xmlResponse;

            try {
                JAXBUtil jaxbUtil = PreviousQueryJAXBUtil.getJAXBUtil();
                JAXBElement jaxbElement = jaxbUtil.unMashallFromString(xmlResponse);
                ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue();

                BodyType bt = messageType.getMessageBody();
                InstanceResponseType instanceResponseType = (InstanceResponseType) new JAXBUnWrapHelper()
                        .getObjectByClass(bt.getAny(), InstanceResponseType.class);

                for (QueryInstanceType queryInstanceType : instanceResponseType.getQueryInstance()) {
                    //change later for working with new xml schema
                    //RunQuery runQuery = queryInstanceType.getResult().get(i).getRunQuery().get(0);

                    QueryInstanceData runData = new QueryInstanceData();

                    runData.visualAttribute("FA");
                    runData.tooltip("The results of the query run");
                    runData.id(new Integer(queryInstanceType.getQueryInstanceId()).toString());
                    //runData.patientRefId(new Integer(queryInstanceType.getRefId()).toString());
                    //runData.patientCount(new Long(queryInstanceType.getCount()).toString());
                    XMLGregorianCalendar cldr = queryInstanceType.getStartDate();
                    runData.name("Results of " + "[" + addZero(cldr.getMonth()) + "-" + addZero(cldr.getDay())
                            + "-" + addZero(cldr.getYear()) + " " + addZero(cldr.getHour()) + ":"
                            + addZero(cldr.getMinute()) + ":" + addZero(cldr.getSecond()) + "]");

                    data.runs.add(runData);
                    addNode(runData, node);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            jTree1.scrollPathToVisible(new TreePath(node.getPath()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if (node.getUserObject().getClass().getSimpleName().equalsIgnoreCase("QueryInstanceData")) {
        QueryInstanceData data = (QueryInstanceData) node.getUserObject();

        try {
            String xmlRequest = data.writeContentQueryXML();
            lastRequestMessage = xmlRequest;
            //System.out.println(xmlRequest);

            String xmlResponse = QueryListNamesClient.sendQueryRequestREST(xmlRequest);
            if (xmlResponse.equalsIgnoreCase("CellDown")) {
                final JPanel parent = this;
                java.awt.EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        JOptionPane.showMessageDialog(parent,
                                "Trouble with connection to the remote server, "
                                        + "this is often a network error, please try again",
                                "Network Error", JOptionPane.INFORMATION_MESSAGE);
                    }
                });
                return;
            }
            lastResponseMessage = xmlResponse;

            JAXBUtil jaxbUtil = PreviousQueryJAXBUtil.getJAXBUtil();

            JAXBElement jaxbElement = jaxbUtil.unMashallFromString(xmlResponse);
            ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue();
            BodyType bt = messageType.getMessageBody();
            ResultResponseType resultResponseType = (ResultResponseType) new JAXBUnWrapHelper()
                    .getObjectByClass(bt.getAny(), ResultResponseType.class);

            for (QueryResultInstanceType queryResultInstanceType : resultResponseType
                    .getQueryResultInstance()) {
                String status = queryResultInstanceType.getQueryStatusType().getName();

                QueryResultData resultData = new QueryResultData();
                resultData.visualAttribute("LAO");
                resultData.tooltip("A patient set of the query run");
                //resultData.queryId(data.queryId());
                resultData.patientRefId(new Integer(queryResultInstanceType.getResultInstanceId()).toString());//data.patientRefId());
                resultData.patientCount(new Integer(queryResultInstanceType.getSetSize()).toString());//data.patientCount());
                if (status.equalsIgnoreCase("FINISHED")) {
                    resultData.name("Patient Set - " + resultData.patientCount() + " Patients");
                } else {
                    resultData.name("Patient Set - " + status);
                }
                resultData.xmlContent(xmlResponse);

                addNode(resultData, node);
            }

            jTree1.scrollPathToVisible(new TreePath(node.getPath()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //implement for other type of nodes later!!!
}

From source file:edu.harvard.i2b2.previousquery.QueryPreviousRunsPanel.java

public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equalsIgnoreCase("Rename ...")) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getSelectionPath().getLastPathComponent();
        QueryMasterData ndata = (QueryMasterData) node.getUserObject();
        Object inputValue = JOptionPane.showInputDialog(this, "Rename this query to: ", "Rename Query Dialog",
                JOptionPane.PLAIN_MESSAGE, null, null,
                ndata.name().substring(0, ndata.name().lastIndexOf("[") - 1));

        if (inputValue != null) {
            String newQueryName = (String) inputValue;
            String requestXml = ndata.writeRenameQueryXML(newQueryName);
            lastRequestMessage = requestXml;

            setCursor(new Cursor(Cursor.WAIT_CURSOR));

            String response = QueryListNamesClient.sendQueryRequestREST(requestXml);
            if (response.equalsIgnoreCase("CellDown")) {
                final JPanel parent = this;
                java.awt.EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        JOptionPane.showMessageDialog(parent,
                                "Trouble with connection to the remote server, "
                                        + "this is often a network error, please try again",
                                "Network Error", JOptionPane.INFORMATION_MESSAGE);
                    }//from   ww  w .j  av  a  2s  .  co  m
                });
                setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                return;
            }
            lastResponseMessage = response;

            if (response != null) {
                JAXBUtil jaxbUtil = PreviousQueryJAXBUtil.getJAXBUtil();

                try {
                    JAXBElement jaxbElement = jaxbUtil.unMashallFromString(response);
                    ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue();
                    StatusType statusType = messageType.getResponseHeader().getResultStatus().getStatus();
                    String status = statusType.getType();

                    if (status.equalsIgnoreCase("DONE")) {
                        ndata.name(newQueryName + " [" + ndata.userId() + "]");
                        node.setUserObject(ndata);
                        //DefaultMutableTreeNode parent = (DefaultMutableTreeNode) node.getParent();

                        jTree1.repaint();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        }
    } else if (e.getActionCommand().equalsIgnoreCase("Delete")) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getSelectionPath().getLastPathComponent();
        QueryMasterData ndata = (QueryMasterData) node.getUserObject();
        Object selectedValue = JOptionPane.showConfirmDialog(this, "Delete Query \"" + ndata.name() + "\"?",
                "Delete Query Dialog", JOptionPane.YES_NO_OPTION);
        if (selectedValue.equals(JOptionPane.YES_OPTION)) {
            System.out.println("delete " + ndata.name());
            String requestXml = ndata.writeDeleteQueryXML();
            lastRequestMessage = requestXml;
            //System.out.println(requestXml);

            setCursor(new Cursor(Cursor.WAIT_CURSOR));

            String response = QueryListNamesClient.sendQueryRequestREST(requestXml);
            if (response.equalsIgnoreCase("CellDown")) {
                final JPanel parent = this;
                java.awt.EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        JOptionPane.showMessageDialog(parent,
                                "Trouble with connection to the remote server, "
                                        + "this is often a network error, please try again",
                                "Network Error", JOptionPane.INFORMATION_MESSAGE);
                    }
                });
                setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                return;
            }
            lastResponseMessage = response;

            if (response != null) {
                JAXBUtil jaxbUtil = PreviousQueryJAXBUtil.getJAXBUtil();

                try {
                    JAXBElement jaxbElement = jaxbUtil.unMashallFromString(response);
                    ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue();
                    StatusType statusType = messageType.getResponseHeader().getResultStatus().getStatus();
                    String status = statusType.getType();

                    if (status.equalsIgnoreCase("DONE")) {
                        treeModel.removeNodeFromParent(node);

                        //jTree1.repaint();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        }
    } else if (e.getActionCommand().equalsIgnoreCase("Refresh All")) {
        String status = loadPreviousQueries(false);
        if (status.equalsIgnoreCase("")) {
            reset(200, false);
        } else if (status.equalsIgnoreCase("CellDown")) {
            final JPanel parent = this;
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    JOptionPane.showMessageDialog(parent,
                            "Trouble with connection to the remote server, "
                                    + "this is often a network error, please try again",
                            "Network Error", JOptionPane.INFORMATION_MESSAGE);
                }
            });
        }
    }
}

From source file:edu.harvard.i2b2.eclipse.plugins.workplace.views.TreeNode.java

public void updateFolders(final Display theDisplay, final TreeViewer theViewer) {
    try {//from  w  ww  .j  a va  2 s  .  co m
        GetReturnType request = new GetReturnType();
        request.setType("core");

        GetChildrenResponseMessage msg = new GetChildrenResponseMessage();
        StatusType procStatus = null;
        String response = null;
        while (procStatus == null || !procStatus.getType().equals("DONE")) {
            //String response = null;
            if (Boolean.parseBoolean(System.getProperty("WPManager")))
                response = WorkplaceServiceDriver.getHomeFoldersByProject(request);
            else
                response = WorkplaceServiceDriver.getHomeFoldersByUserId(request);
            procStatus = msg.processResult(response);

            //            if  other error codes
            //            TABLE_ACCESS_DENIED and USER_INVALID
            if (procStatus.getType().equals("ERROR")) {

                System.setProperty("errorMessage", procStatus.getValue());

                return;
            }
            procStatus.setType("DONE");
        }

        JAXBElement jaxbElement = WorkplaceJAXBUtil.getJAXBUtil().unMashallFromString(response);
        ResponseMessageType respMessageType = (ResponseMessageType) jaxbElement.getValue();
        String version = respMessageType.getMessageHeader().getSendingApplication().getApplicationVersion();
        System.setProperty("wkplServerVersion", version);
        double vernum = Double.parseDouble(version);
        log.info("Workplace server version: " + version);

        FoldersType allFolders = msg.doReadFolders();
        List folders = allFolders.getFolder();
        getNodesFromXMLString(folders);
    } catch (AxisFault e) {
        log.error(e.getMessage());
        System.setProperty("errorMessage", "Workplace cell is unavailable");
    } catch (I2B2Exception e) {
        log.error(e.getMessage());
        System.setProperty("errorMessage", e.getMessage());
    } catch (Exception e) {
        log.error(e.getMessage());
        System.setProperty("errorMessage", "Remote server is unavailable");

    }
}

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

public RootXNode serializeAtomicValue(JAXBElement<?> element) throws SchemaException {
    Validate.notNull(element);//from w ww.j a v  a2s .c  o  m
    return serializeAtomicValue(element.getValue(), element.getName(), null);
}

From source file:it.cnr.icar.eric.server.query.QueryManagerImpl.java

/**
 * submitAdhocQuery/*ww  w  .ja  va 2s  .c o  m*/
 */
@SuppressWarnings({ "static-access", "unchecked" })
public AdhocQueryResponse submitAdhocQuery(RequestContext context) throws RegistryException {

    AdhocQueryResponse ebAdhocQueryResponse = null;
    context = ServerRequestContext.convert(context);

    AdhocQueryRequest ebAdhocQueryRequest = (AdhocQueryRequest) ((ServerRequestContext) context)
            .getCurrentRegistryRequest();
    ResponseOptionType ebResponseOptionType = ebAdhocQueryRequest.getResponseOption();
    ReturnType returnType = ebResponseOptionType.getReturnType();

    UserType user = ((ServerRequestContext) context).getUser();

    // The result of the query
    RegistryObjectListType ebRegistryObjectListType = null;

    try {
        ebAdhocQueryResponse = null;

        // Process request for the case where it is a parameterized
        // invocation of a stored query
        processForParameterizedQuery((ServerRequestContext) context);

        // TODO: May need a better way than checking
        // getSpecialQueryResults() to know if specialQuery was called.
        if (((ServerRequestContext) context).getSpecialQueryResults() != null) {
            ebAdhocQueryResponse = processForSpecialQueryResults((ServerRequestContext) context);
        } else {
            // Check if it is a federated query and process it using
            // FederatedQueryManager if so.
            boolean isFederated = ebAdhocQueryRequest.isFederated();
            if (isFederated) {
                // Initialize lazily. Otherwise we have an infinite create
                // loop
                if (fqm == null) {
                    fqm = FederatedQueryManager.getInstance();
                }
                ebAdhocQueryResponse = fqm.submitAdhocQuery((ServerRequestContext) context);
            } else {
                int startIndex = ebAdhocQueryRequest.getStartIndex().intValue();
                int maxResults = ebAdhocQueryRequest.getMaxResults().intValue();
                IterativeQueryParams paramHolder = new IterativeQueryParams(startIndex, maxResults);

                org.oasis.ebxml.registry.bindings.rim.AdhocQueryType adhocQuery = ebAdhocQueryRequest
                        .getAdhocQuery();

                QueryExpressionType queryExp = adhocQuery.getQueryExpression();
                String queryLang = queryExp.getQueryLanguage();
                if (queryLang.equals(BindingUtility.CANONICAL_QUERY_LANGUAGE_ID_SQL_92)) {
                    String queryStr = (String) queryExp.getContent().get(0);
                    queryStr = replaceSpecialVariables(user, queryStr);

                    ebRegistryObjectListType = sqlQueryProcessor.executeQuery((ServerRequestContext) context,
                            user, queryStr, ebResponseOptionType, paramHolder);

                    processDepthParameter((ServerRequestContext) context);

                    ebAdhocQueryResponse = BindingUtility.getInstance().queryFac.createAdhocQueryResponse();

                    ebAdhocQueryResponse.setRegistryObjectList(ebRegistryObjectListType);
                    ebAdhocQueryResponse.setStatus(BindingUtility.CANONICAL_RESPONSE_STATUS_TYPE_ID_Success);
                    ebAdhocQueryResponse.setStartIndex(BigInteger.valueOf(paramHolder.startIndex));
                    ebAdhocQueryResponse.setTotalResultCount(BigInteger.valueOf(paramHolder.totalResultCount));

                } else if (queryLang.equals(BindingUtility.CANONICAL_QUERY_LANGUAGE_ID_ebRSFilterQuery)) {
                    String queryStr = (String) queryExp.getContent().get(0);
                    Unmarshaller unmarshaller = BindingUtility.getInstance().getJAXBContext()
                            .createUnmarshaller();
                    JAXBElement<FilterQueryType> ebFilterQuery = (JAXBElement<FilterQueryType>) unmarshaller
                            .unmarshal(new StreamSource(new StringReader(queryStr)));

                    // take ComplexType from Element
                    FilterQueryType filterQuery = ebFilterQuery.getValue();

                    //                  FilterQueryType filterQuery = (FilterQueryType) queryExp.getContent().get(0);

                    ebRegistryObjectListType = filterQueryProcessor.executeQuery(
                            ((ServerRequestContext) context), user, filterQuery, ebResponseOptionType,
                            paramHolder);

                    ebAdhocQueryResponse = BindingUtility.getInstance().queryFac.createAdhocQueryResponse();
                    ebAdhocQueryResponse.setRegistryObjectList(ebRegistryObjectListType);
                    ebAdhocQueryResponse.setStatus(BindingUtility.CANONICAL_RESPONSE_STATUS_TYPE_ID_Success);
                    ebAdhocQueryResponse.setStartIndex(BigInteger.valueOf(paramHolder.startIndex));
                    ebAdhocQueryResponse.setTotalResultCount(BigInteger.valueOf(paramHolder.totalResultCount));

                } else {
                    throw new UnsupportedCapabilityException(
                            "Unsupported Query Language: ClassificationNode id: " + queryLang);
                }
            }
        }

        // fetch child objects
        if (fetchChildObjsSrv) {
            HashMap<String, Object> slotsMap = bu.getSlotsFromRequest(ebAdhocQueryRequest);
            boolean fetchChildObjsClt = Boolean
                    .valueOf((String) slotsMap.get(CanonicalConstants.CANONICAL_SLOT_GET_CHILD_OBJECTS))
                    .booleanValue();
            if (fetchChildObjsClt) {
                fetchChildObjects(ebAdhocQueryResponse.getRegistryObjectList().getIdentifiable(),
                        (ServerRequestContext) context, ebResponseOptionType);
            }
        }

        // Add repositoryItems to repositoryItemMap if so requested in
        // responseOption
        if (returnType == returnType.LEAF_CLASS_WITH_REPOSITORY_ITEM) {
            addRepositoryItems(ebAdhocQueryResponse.getRegistryObjectList().getIdentifiable(), context);
        }

        if (!bypassCMS) {
            // Now perform any Role-Based Content Filtering on query results
            ((ServerRequestContext) context).getQueryResults().clear();
            ((ServerRequestContext) context).getQueryResults()
                    .addAll(ebAdhocQueryResponse.getRegistryObjectList().getIdentifiable());

            cmsm.invokeServices(((ServerRequestContext) context));
            ebAdhocQueryResponse.getRegistryObjectList().getIdentifiable().clear();
            ebAdhocQueryResponse.getRegistryObjectList().getIdentifiable()
                    .addAll(((ServerRequestContext) context).getQueryResults());

            ((ServerRequestContext) context).getQueryResults().clear();
        }
    } catch (RegistryException e) {
        ((ServerRequestContext) context).rollback();
        throw e;
    } catch (Exception e) {
        ((ServerRequestContext) context).rollback();

        throw new RegistryException(e);
    }

    removeObjectsDeniedAccess(((ServerRequestContext) context),
            ebAdhocQueryResponse.getRegistryObjectList().getIdentifiable());

    if (isQueryFilterRequestBeingMade((ServerRequestContext) context)) {
        // Handle filter query requests
        processForQueryFilterPlugins((ServerRequestContext) context);
        // Filter queries produce special query results
        ebAdhocQueryResponse = processForSpecialQueryResults((ServerRequestContext) context);
    }

    ((ServerRequestContext) context).commit();
    ebAdhocQueryResponse.setRequestId(ebAdhocQueryRequest.getId());

    return ebAdhocQueryResponse;
}

From source file:at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorServlet.java

/**
 * Handles the reception of a STORK response message
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *///from  w w w . j  a va2 s  .c  om
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String pendingRequestID = null;

    try {

        Logger.warn(getClass().getName() + " is deprecated and should not be used any more.");

        Logger.info("PEPSConnector Servlet invoked, expecting C-PEPS message.");
        Logger.debug("This ACS endpoint is: " + HTTPUtils.getBaseURL(request));

        super.setNoCachingHeadersInHttpRespone(request, response);
        Logger.trace("No Caching headers set for HTTP response");

        //check if https or only http
        super.checkIfHTTPisAllowed(request.getRequestURL().toString());

        Logger.debug("Beginning to extract SAMLResponse out of HTTP Request");

        //extract STORK Response from HTTP Request
        //Decodes SAML Response
        byte[] decSamlToken;
        try {
            decSamlToken = PEPSUtil.decodeSAMLToken(request.getParameter("SAMLResponse"));
            Logger.debug("SAMLResponse: " + new String(decSamlToken));

        } catch (NullPointerException e) {
            Logger.error("Unable to retrieve STORK Response", e);
            throw new MOAIDException("stork.04", null);
        }

        //Get SAMLEngine instance
        STORKSAMLEngine engine = STORKSAMLEngine.getInstance("outgoing");

        STORKAuthnResponse authnResponse = null;
        try {
            //validate SAML Token
            Logger.debug("Starting validation of SAML response");
            authnResponse = engine.validateSTORKAuthnResponse(decSamlToken, (String) request.getRemoteHost());
            Logger.info("SAML response succesfully verified!");
        } catch (STORKSAMLEngineException e) {
            Logger.error("Failed to verify STORK SAML Response", e);
            throw new MOAIDException("stork.05", null);
        }

        Logger.info("STORK SAML Response message succesfully extracted");
        Logger.debug("STORK response: ");
        Logger.debug(authnResponse.toString());

        Logger.debug("Trying to find MOA Session-ID ...");
        //String moaSessionID = request.getParameter(PARAM_SESSIONID);
        //first use SAML2 relayState 
        String moaSessionID = request.getParameter("RelayState");

        // escape parameter strings
        moaSessionID = StringEscapeUtils.escapeHtml(moaSessionID);

        //check if SAML2 relaystate includes a MOA sessionID
        if (StringUtils.isEmpty(moaSessionID)) {
            //if relaystate is emtpty, use SAML response -> inResponseTo element as session identifier

            moaSessionID = authnResponse.getInResponseTo();
            moaSessionID = StringEscapeUtils.escapeHtml(moaSessionID);

            if (StringUtils.isEmpty(moaSessionID)) {
                //No authentication session has been started before
                Logger.error("MOA-SessionID was not found, no previous AuthnRequest had been started");
                Logger.debug("PEPSConnectorURL was: " + request.getRequestURL());
                throw new AuthenticationException("auth.02", new Object[] { moaSessionID });

            } else
                Logger.trace(
                        "Use MOA SessionID " + moaSessionID + " from AuthnResponse->inResponseTo attribute.");

        } else
            //Logger.trace("MOA SessionID " + moaSessionID + " is found in http GET parameter.");
            Logger.trace("MOA SessionID " + moaSessionID + " is found in SAML2 relayState.");

        /*INFO!!!!
         * SAML message IDs has an different format then MOASessionIDs
         * This is only a workaround because many PEPS does not support SAML2 relayState or
         * MOASessionID as AttributConsumerServiceURL GET parameter
        */
        //            if (!ParamValidatorUtils.isValidSessionID(moaSessionID))
        //                throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_SESSIONID, "auth.12");

        pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moaSessionID);

        //load MOASession from database
        AuthenticationSession moaSession = AuthenticationServer.getSession(moaSessionID);
        //change MOASessionID
        moaSessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);

        Logger.info("Found MOA sessionID: " + moaSessionID);

        String statusCodeValue = authnResponse.getStatusCode();

        if (!statusCodeValue.equals(StatusCode.SUCCESS_URI)) {
            Logger.error("Received ErrorResponse from PEPS: " + statusCodeValue);
            throw new MOAIDException("stork.06", new Object[] { statusCodeValue });
        }

        Logger.info("Got SAML response with authentication success message.");

        Logger.debug("MOA session is still valid");

        STORKAuthnRequest storkAuthnRequest = moaSession.getStorkAuthnRequest();

        if (storkAuthnRequest == null) {
            Logger.error(
                    "Could not find any preceeding STORK AuthnRequest to this MOA session: " + moaSessionID);
            throw new MOAIDException("stork.07", null);
        }

        OAAuthParameter oaParam = AuthConfigurationProvider.getInstance()
                .getOnlineApplicationParameter(moaSession.getPublicOAURLPrefix());
        if (oaParam == null)
            throw new AuthenticationException("auth.00", new Object[] { moaSession.getPublicOAURLPrefix() });
        //================== Check QAA level start ====================
        int reqQaa = -1;
        int authQaa = -1;
        String authQaaStr = null;
        try {
            reqQaa = storkAuthnRequest.getQaa();

            //TODO: found better solution, but QAA Level in response could be not supported yet
            try {

                authQaaStr = authnResponse.getAssertions().get(0).getAuthnStatements().get(0).getAuthnContext()
                        .getAuthnContextClassRef().getAuthnContextClassRef();
                moaSession.setQAALevel(authQaaStr);

            } catch (Throwable e) {
                Logger.warn("STORK QAA-Level is not found in AuthnResponse. Set QAA Level to requested level");
                moaSession.setQAALevel(PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel());
                authQaaStr = PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel();
            }
            if (authQaaStr != null)//Check value only if set
            {
                authQaa = Integer.valueOf(authQaaStr.substring(PVPConstants.STORK_QAA_PREFIX.length()));
                //               authQaa = Integer.valueOf(authQaaStr);
                if (reqQaa > authQaa) {
                    Logger.warn("Requested QAA level does not match to authenticated QAA level");
                    throw new MOAIDException("stork.21", new Object[] { reqQaa, authQaa });

                }
            }
        } catch (MOAIDException e) {
            throw e;

        } catch (Exception e) {
            if (Logger.isDebugEnabled())
                Logger.warn("STORK QAA Level evaluation error", e);

            else
                Logger.warn("STORK QAA Level evaluation error (ErrorMessage=" + e.getMessage() + ")");

            throw new MOAIDException("stork.21", new Object[] { reqQaa, authQaa });

        }
        //================== Check QAA level end ====================

        Logger.debug("Found a preceeding STORK AuthnRequest to this MOA session: " + moaSessionID);

        ////////////// incorporate gender from parameters if not in stork response

        IPersonalAttributeList attributeList = authnResponse.getPersonalAttributeList();

        // but first, check if we have a representation case
        if (STORKResponseProcessor.hasAttribute("mandateContent", attributeList)
                || STORKResponseProcessor.hasAttribute("representative", attributeList)
                || STORKResponseProcessor.hasAttribute("represented", attributeList)) {
            // in a representation case...
            moaSession.setUseMandate("true");

            // and check if we have the gender value
            PersonalAttribute gender = attributeList.get("gender"); // TODO Do we need to check gender value if there is no representation case?
            if (null == gender) {
                String gendervalue = (String) request.getParameter("gender");
                if (null != gendervalue) {
                    gender = new PersonalAttribute();
                    gender.setName("gender");
                    ArrayList<String> tmp = new ArrayList<String>();
                    tmp.add(gendervalue);
                    gender.setValue(tmp);

                    authnResponse.getPersonalAttributeList().add(gender);
                }
            }
        }

        //////////////////////////////////////////////////////////////////////////

        Logger.debug("Starting extraction of signedDoc attribute");
        //extract signed doc element and citizen signature
        String citizenSignature = null;
        try {
            String signatureInfo = authnResponse.getPersonalAttributeList().get("signedDoc").getValue().get(0); // TODO ERROR HANDLING

            Logger.debug("signatureInfo:" + signatureInfo);

            SignResponse dssSignResponse = (SignResponse) ApiUtils
                    .unmarshal(new StreamSource(new java.io.StringReader(signatureInfo)));

            // fetch signed doc
            DataSource ds = null;
            try {
                ds = LightweightSourceResolver.getDataSource(dssSignResponse);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (ds == null) {
                //Normal DocumentServices return a http-page, but the SI DocumentService returns HTTP error 500 
                //which results in an exception and ds==null

                //try to load document from documentservice
                citizenSignature = loadDocumentFromDocumentService(dssSignResponse);
                //throw new ApiUtilsException("No datasource found in response");
            } else {
                InputStream incoming = ds.getInputStream();
                citizenSignature = IOUtils.toString(incoming);
                incoming.close();

                Logger.debug("citizenSignature:" + citizenSignature);
                if (isDocumentServiceUsed(citizenSignature) == true) {
                    citizenSignature = loadDocumentFromDocumentService(dssSignResponse);
                    //               Logger.debug("Loading document from DocumentService.");
                    //               String url = getDtlUrlFromResponse(dssSignResponse);
                    //               //get Transferrequest
                    //               String transferRequest = getDocTransferRequest(dssSignResponse.getDocUI(), url);
                    //               //Load document from DocumentService
                    //               byte[] data = getDocumentFromDtl(transferRequest, url);
                    //               citizenSignature = new String(data, "UTF-8");
                    //               Logger.debug("Overridung citizenSignature with:"+citizenSignature);
                }
            }
            JAXBContext ctx = JAXBContext.newInstance(SignatureType.class.getPackage().getName());
            SignatureType root = ((JAXBElement<SignatureType>) ctx.createUnmarshaller()
                    .unmarshal(IOUtils.toInputStream(citizenSignature))).getValue();

            // memorize signature into authblock
            moaSession.setAuthBlock(citizenSignature);

            // extract certificate
            for (Object current : root.getKeyInfo().getContent())
                if (((JAXBElement<?>) current).getValue() instanceof X509DataType) {
                    for (Object currentX509Data : ((JAXBElement<X509DataType>) current).getValue()
                            .getX509IssuerSerialOrX509SKIOrX509SubjectName()) {
                        JAXBElement<?> casted = ((JAXBElement<?>) currentX509Data);
                        if (casted.getName().getLocalPart().equals("X509Certificate")) {
                            moaSession.setSignerCertificate(
                                    new X509Certificate(((String) casted.getValue()).getBytes("UTF-8")));
                            break;
                        }
                    }
                }

        } catch (Throwable e) {
            Logger.error("Could not extract citizen signature from C-PEPS", e);
            throw new MOAIDException("stork.09", null);
        }
        Logger.debug("Foregin Citizen signature successfully extracted from STORK Assertion (signedDoc)");
        Logger.debug("Citizen signature will be verified by SZR Gateway!");

        Logger.debug("fetching OAParameters from database");

        //         //read configuration paramters of OA
        //           AuthenticationSession moasession;
        //         try {
        //            moasession = AuthenticationSessionStoreage.getSession(moaSessionID);
        //         } catch (MOADatabaseException e2) {
        //            Logger.error("could not retrieve moa session");
        //            throw new AuthenticationException("auth.01", null);
        //         }
        //          OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(moaSession.getPublicOAURLPrefix());
        //          if (oaParam == null)
        //                throw new AuthenticationException("auth.00", new Object[] { moaSession.getPublicOAURLPrefix() });

        // retrieve target
        //TODO: check in case of SSO!!!
        String targetType = null;
        if (oaParam.getBusinessService()) {
            String id = oaParam.getIdentityLinkDomainIdentifier();
            if (id.startsWith(AuthenticationSession.REGISTERANDORDNR_PREFIX_))
                targetType = id;
            else
                targetType = AuthenticationSession.REGISTERANDORDNR_PREFIX_ + moaSession.getDomainIdentifier();
        } else {
            targetType = AuthenticationSession.TARGET_PREFIX_ + oaParam.getTarget();
        }

        IdentityLink identityLink = null;
        try {
            AuthConfigurationProvider config = AuthConfigurationProvider.getInstance();
            if (config.isStorkFakeIdLActive()
                    && config.getStorkFakeIdLCountries().contains(storkAuthnRequest.getCitizenCountryCode())) {
                // create fake IdL
                // - fetch IdL template from resources
                InputStream s = PEPSConnectorServlet.class
                        .getResourceAsStream("/resources/xmldata/fakeIdL_IdL_template.xml");
                Element idlTemplate = DOMUtils.parseXmlValidating(s);

                identityLink = new IdentityLinkAssertionParser(idlTemplate).parseIdentityLink();

                // replace data
                Element idlassertion = identityLink.getSamlAssertion();
                // - set bpk/wpbk;
                Node prIdentification = XPathUtils.selectSingleNode(idlassertion,
                        IdentityLinkAssertionParser.PERSON_IDENT_VALUE_XPATH);
                if (!STORKResponseProcessor.hasAttribute("eIdentifier", attributeList))
                    throw new STORKException("eIdentifier is missing");
                String eIdentifier = STORKResponseProcessor.getAttributeValue("eIdentifier", attributeList,
                        false);
                prIdentification.getFirstChild().setNodeValue(eIdentifier);

                // - set last name
                Node prFamilyName = XPathUtils.selectSingleNode(idlassertion,
                        IdentityLinkAssertionParser.PERSON_FAMILY_NAME_XPATH);
                if (!STORKResponseProcessor.hasAttribute("surname", attributeList))
                    throw new STORKException("surname is missing");
                String familyName = STORKResponseProcessor.getAttributeValue("surname", attributeList, false);
                prFamilyName.getFirstChild().setNodeValue(familyName);

                // - set first name
                Node prGivenName = XPathUtils.selectSingleNode(idlassertion,
                        IdentityLinkAssertionParser.PERSON_GIVEN_NAME_XPATH);
                if (!STORKResponseProcessor.hasAttribute("givenName", attributeList))
                    throw new STORKException("givenName is missing");
                String givenName = STORKResponseProcessor.getAttributeValue("givenName", attributeList, false);
                prGivenName.getFirstChild().setNodeValue(givenName);

                // - set date of birth
                Node prDateOfBirth = XPathUtils.selectSingleNode(idlassertion,
                        IdentityLinkAssertionParser.PERSON_DATE_OF_BIRTH_XPATH);
                if (!STORKResponseProcessor.hasAttribute("dateOfBirth", attributeList))
                    throw new STORKException("dateOfBirth is missing");
                String dateOfBirth = STORKResponseProcessor.getAttributeValue("dateOfBirth", attributeList,
                        false);
                prDateOfBirth.getFirstChild().setNodeValue(dateOfBirth);

                identityLink = new IdentityLinkAssertionParser(idlassertion).parseIdentityLink();

                //resign IDL
                IdentityLinkReSigner identitylinkresigner = IdentityLinkReSigner.getInstance();
                Element resignedilAssertion = identitylinkresigner.resignIdentityLink(
                        identityLink.getSamlAssertion(), config.getStorkFakeIdLResigningKey());
                identityLink = new IdentityLinkAssertionParser(resignedilAssertion).parseIdentityLink();
            } else {
                //contact SZR Gateway
                Logger.debug("Starting connecting SZR Gateway");
                identityLink = STORKResponseProcessor.connectToSZRGateway(
                        authnResponse.getPersonalAttributeList(), oaParam.getFriendlyName(), targetType, null,
                        oaParam.getMandateProfiles(), citizenSignature);
            }
        } catch (STORKException e) {
            // this is really nasty but we work against the system here. We are supposed to get the gender attribute from
            // stork. If we do not, we cannot register the person in the ERnP - we have to have the
            // gender for the represented person. So here comes the dirty hack. 
            if (e.getCause() instanceof STORKException
                    && e.getCause().getMessage().equals("gender not found in response")) {
                try {
                    Logger.trace("Initialize VelocityEngine...");

                    VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine();
                    Template template = velocityEngine.getTemplate("/resources/templates/fetchGender.html");
                    VelocityContext context = new VelocityContext();
                    context.put("SAMLResponse", request.getParameter("SAMLResponse"));
                    context.put("action", request.getRequestURL());

                    StringWriter writer = new StringWriter();
                    template.merge(context, writer);

                    response.getOutputStream().write(writer.toString().getBytes("UTF-8"));
                } catch (Exception e1) {
                    Logger.error("Error sending gender retrival form.", e1);
                    //                  httpSession.invalidate();
                    throw new MOAIDException("stork.10", null);
                }

                return;
            }

            Logger.error("Error connecting SZR Gateway", e);
            throw new MOAIDException("stork.10", null);
        }
        Logger.debug("SZR communication was successfull");

        if (identityLink == null) {
            Logger.error("SZR Gateway did not return an identity link.");
            throw new MOAIDException("stork.10", null);
        }
        moaSession.setForeigner(true);

        Logger.info("Received Identity Link from SZR Gateway");
        moaSession.setIdentityLink(identityLink);

        Logger.debug("Adding addtional STORK attributes to MOA session");
        moaSession.setStorkAttributes(authnResponse.getPersonalAttributeList());

        Logger.debug("Add full STORK AuthnResponse to MOA session");
        moaSession.setStorkAuthnResponse(request.getParameter("SAMLResponse"));

        //We don't have BKUURL, setting from null to "Not applicable"
        moaSession.setBkuURL("Not applicable (STORK Authentication)");

        // free for single use
        moaSession.setAuthenticatedUsed(false);

        // stork did the authentication step
        moaSession.setAuthenticated(true);

        //         //TODO: found better solution, but QAA Level in response could be not supported yet
        //         try {
        //
        //            moaSession.setQAALevel(authnResponse.getAssertions().get(0).
        //                  getAuthnStatements().get(0).getAuthnContext().
        //                  getAuthnContextClassRef().getAuthnContextClassRef());
        //            
        //         } catch (Throwable e) {
        //            Logger.warn("STORK QAA-Level is not found in AuthnResponse. Set QAA Level to requested level");
        //            moaSession.setQAALevel(PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel());
        //            
        //         }

        //session is implicit stored in changeSessionID!!!!
        String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);

        Logger.info("Changed MOASession " + moaSessionID + " to Session " + newMOASessionID);

        //redirect
        String redirectURL = null;
        redirectURL = new DataURLBuilder().buildDataURL(moaSession.getAuthURL(),
                ModulUtils.buildAuthURL(moaSession.getModul(), moaSession.getAction(), pendingRequestID),
                newMOASessionID);
        redirectURL = response.encodeRedirectURL(redirectURL);

        //          response.setContentType("text/html");
        //          response.setStatus(302);
        //          response.addHeader("Location", redirectURL);
        response.sendRedirect(redirectURL);
        Logger.info("REDIRECT TO: " + redirectURL);

    } catch (AuthenticationException e) {
        handleError(null, e, request, response, pendingRequestID);

    } catch (MOAIDException e) {
        handleError(null, e, request, response, pendingRequestID);

    } catch (Exception e) {
        Logger.error("PEPSConnector has an interal Error.", e);
    }

    finally {
        ConfigurationDBUtils.closeSession();
    }

}

From source file:com.bluexml.xforms.controller.alfresco.agents.MappingAgent.java

/**
 * Gets the name of all custom forms available in the mapping file.
 * /*from   w  w  w .j  a  v a2s. c o  m*/
 * @return the list
 */
public List<String> getAllCustomForms() {
    List<JAXBElement<? extends CanisterType>> elements = mapping.getCanister();

    List<String> result = new ArrayList<String>();
    for (JAXBElement<? extends CanisterType> element : elements) {
        if (element.getValue() instanceof FormType) {
            FormType elt = (FormType) element.getValue();
            result.add(elt.getName());
        }
    }
    return result;
}

From source file:com.bluexml.xforms.controller.alfresco.agents.MappingAgent.java

/**
 * Gets the list of all search forms available in the mapping file.
 * /*from  w  w  w .  j a v a  2  s  . c  om*/
 * @return the list
 */
public List<String> getAllSearchForms() {
    List<JAXBElement<? extends CanisterType>> elements = mapping.getCanister();

    List<String> result = new ArrayList<String>();
    for (JAXBElement<? extends CanisterType> element : elements) {
        if (element.getValue() instanceof SearchFormType) {
            SearchFormType elt = (SearchFormType) element.getValue();
            result.add(elt.getName());
        }
    }
    return result;
}