Example usage for javax.xml.namespace QName equals

List of usage examples for javax.xml.namespace QName equals

Introduction

In this page you can find the example usage for javax.xml.namespace QName equals.

Prototype

public final boolean equals(Object objectToTest) 

Source Link

Document

Test this QName for equality with another Object.

If the Object to be tested is not a QName or is null, then this method returns false.

Two QNames are considered equal if and only if both the Namespace URI and local part are equal.

Usage

From source file:com.evolveum.midpoint.model.test.AbstractModelIntegrationTest.java

protected <F extends FocusType> void assertAssignedNo(PrismObject<F> user, QName refType) {
    F userType = user.asObjectable();/*from   w w  w  .j av a2 s .c om*/
    for (AssignmentType assignmentType : userType.getAssignment()) {
        ObjectReferenceType targetRef = assignmentType.getTargetRef();
        if (targetRef != null) {
            if (refType.equals(targetRef.getType())) {
                AssertJUnit.fail(user + " has role " + targetRef.getOid() + " while expected no roles");
            }
        }
    }
}

From source file:com.twinsoft.convertigo.engine.migration.Migration7_0_0.java

public static void migrate(final String projectName) {
    try {//  w  ww.ja v a  2 s. c o  m
        Map<String, Reference> referenceMap = new HashMap<String, Reference>();
        XmlSchema projectSchema = null;

        Project project = Engine.theApp.databaseObjectsManager.getOriginalProjectByName(projectName, false);

        // Copy all xsd files to project's xsd directory
        File destDir = new File(project.getXsdDirPath());
        copyXsdOfProject(projectName, destDir);

        String projectWsdlFilePath = Engine.PROJECTS_PATH + "/" + projectName + "/" + projectName + ".wsdl";
        File wsdlFile = new File(projectWsdlFilePath);

        String projectXsdFilePath = Engine.PROJECTS_PATH + "/" + projectName + "/" + projectName + ".xsd";
        File xsdFile = new File(projectXsdFilePath);

        if (xsdFile.exists()) {
            // Load project schema from old XSD file
            XmlSchemaCollection collection = new XmlSchemaCollection();
            collection.setSchemaResolver(new DefaultURIResolver() {
                public InputSource resolveEntity(String targetNamespace, String schemaLocation,
                        String baseUri) {
                    // Case of a c8o project location
                    if (schemaLocation.startsWith("../") && schemaLocation.endsWith(".xsd")) {
                        try {
                            String targetProjectName = schemaLocation.substring(3,
                                    schemaLocation.indexOf("/", 3));
                            File pDir = new File(Engine.PROJECTS_PATH + "/" + targetProjectName);
                            if (pDir.exists()) {
                                File pFile = new File(Engine.PROJECTS_PATH + schemaLocation.substring(2));
                                // Case c8o project is already migrated
                                if (!pFile.exists()) {
                                    Document doc = Engine.theApp.schemaManager
                                            .getSchemaForProject(targetProjectName).getSchemaDocument();
                                    DOMSource source = new DOMSource(doc);
                                    StringWriter writer = new StringWriter();
                                    StreamResult result = new StreamResult(writer);
                                    TransformerFactory.newInstance().newTransformer().transform(source, result);
                                    StringReader reader = new StringReader(writer.toString());
                                    return new InputSource(reader);
                                }
                            }
                            return null;
                        } catch (Exception e) {
                            Engine.logDatabaseObjectManager
                                    .warn("[Migration 7.0.0] Unable to find schema location \"" + schemaLocation
                                            + "\"", e);
                            return null;
                        }
                    } else if (schemaLocation.indexOf("://") == -1 && schemaLocation.endsWith(".xsd")) {
                        return super.resolveEntity(targetNamespace, schemaLocation,
                                Engine.PROJECTS_PATH + "/" + projectName);
                    }
                    return super.resolveEntity(targetNamespace, schemaLocation, baseUri);
                }

            });
            projectSchema = SchemaUtils.loadSchema(new File(projectXsdFilePath), collection);
            ConvertigoError.updateXmlSchemaObjects(projectSchema);
            SchemaMeta.setCollection(projectSchema, collection);

            for (Connector connector : project.getConnectorsList()) {
                for (Transaction transaction : connector.getTransactionsList()) {
                    try {
                        // Migrate transaction in case of a Web Service consumption project
                        if (transaction instanceof XmlHttpTransaction) {
                            XmlHttpTransaction xmlHttpTransaction = (XmlHttpTransaction) transaction;
                            String reqn = xmlHttpTransaction.getResponseElementQName();
                            if (!reqn.equals("")) {
                                boolean useRef = reqn.indexOf(";") == -1;
                                // Doc/Literal case
                                if (useRef) {
                                    try {
                                        String[] qn = reqn.split(":");
                                        QName refName = new QName(
                                                projectSchema.getNamespaceContext().getNamespaceURI(qn[0]),
                                                qn[1]);
                                        xmlHttpTransaction.setXmlElementRefAffectation(new XmlQName(refName));
                                    } catch (Exception e) {
                                    }
                                }
                                // RPC case
                                else {
                                    int index, index2;
                                    try {
                                        index = reqn.indexOf(";");
                                        String opName = reqn.substring(0, index);
                                        if ((index2 = reqn.indexOf(";", index + 1)) != -1) {
                                            String eltName = reqn.substring(index + 1, index2);
                                            String eltType = reqn.substring(index2 + 1);
                                            String[] qn = eltType.split(":");

                                            QName typeName = new QName(
                                                    projectSchema.getNamespaceContext().getNamespaceURI(qn[0]),
                                                    qn[1]);
                                            String responseElementQName = opName + ";" + eltName + ";" + "{"
                                                    + typeName.getNamespaceURI() + "}"
                                                    + typeName.getLocalPart();
                                            xmlHttpTransaction.setResponseElementQName(responseElementQName);
                                        }
                                    } catch (Exception e) {
                                    }
                                }
                            }
                        }

                        // Retrieve required XmlSchemaObjects for transaction
                        QName requestQName = new QName(project.getTargetNamespace(),
                                transaction.getXsdRequestElementName());
                        QName responseQName = new QName(project.getTargetNamespace(),
                                transaction.getXsdResponseElementName());
                        LinkedHashMap<QName, XmlSchemaObject> map = new LinkedHashMap<QName, XmlSchemaObject>();
                        XmlSchemaWalker dw = XmlSchemaWalker.newDependencyWalker(map, true, false);
                        dw.walkByElementRef(projectSchema, requestQName);
                        dw.walkByElementRef(projectSchema, responseQName);

                        // Create transaction schema
                        String targetNamespace = projectSchema.getTargetNamespace();
                        String prefix = projectSchema.getNamespaceContext().getPrefix(targetNamespace);
                        XmlSchema transactionSchema = SchemaUtils.createSchema(prefix, targetNamespace,
                                XsdForm.unqualified.name(), XsdForm.unqualified.name());

                        // Add required prefix declarations
                        List<String> nsList = new LinkedList<String>();
                        for (QName qname : map.keySet()) {
                            String nsURI = qname.getNamespaceURI();
                            if (!nsURI.equals(Constants.URI_2001_SCHEMA_XSD)) {
                                if (!nsList.contains(nsURI)) {
                                    nsList.add(nsURI);
                                }
                            }
                            String nsPrefix = qname.getPrefix();
                            if (!nsURI.equals(targetNamespace)) {
                                NamespaceMap nsMap = SchemaUtils.getNamespaceMap(transactionSchema);
                                if (nsMap.getNamespaceURI(nsPrefix) == null) {
                                    nsMap.add(nsPrefix, nsURI);
                                    transactionSchema.setNamespaceContext(nsMap);
                                }
                            }
                        }

                        // Add required imports
                        for (String namespaceURI : nsList) {
                            XmlSchemaObjectCollection includes = projectSchema.getIncludes();
                            for (int i = 0; i < includes.getCount(); i++) {
                                XmlSchemaObject xmlSchemaObject = includes.getItem(i);
                                if (xmlSchemaObject instanceof XmlSchemaImport) {
                                    if (((XmlSchemaImport) xmlSchemaObject).getNamespace()
                                            .equals(namespaceURI)) {

                                        // do not allow import with same ns !
                                        if (namespaceURI.equals(project.getTargetNamespace()))
                                            continue;

                                        String location = ((XmlSchemaImport) xmlSchemaObject)
                                                .getSchemaLocation();

                                        // This is a convertigo project reference
                                        if (location.startsWith("../")) {
                                            // Copy all xsd files to xsd directory
                                            String targetProjectName = location.substring(3,
                                                    location.indexOf("/", 3));
                                            copyXsdOfProject(targetProjectName, destDir);
                                        }

                                        // Add reference
                                        addReferenceToMap(referenceMap, namespaceURI, location);

                                        // Add import
                                        addImport(transactionSchema, namespaceURI, location);
                                    }
                                }
                            }
                        }

                        QName responseTypeQName = new QName(project.getTargetNamespace(),
                                transaction.getXsdResponseTypeName());

                        // Add required schema objects
                        for (QName qname : map.keySet()) {
                            if (qname.getNamespaceURI().equals(targetNamespace)) {
                                XmlSchemaObject ob = map.get(qname);

                                if (qname.getLocalPart().startsWith("ConvertigoError"))
                                    continue;
                                transactionSchema.getItems().add(ob);

                                // Add missing response error element and attributes
                                if (qname.equals(responseTypeQName)) {
                                    Transaction.addSchemaResponseObjects(transactionSchema,
                                            (XmlSchemaComplexType) ob);
                                }
                            }
                        }

                        // Add missing ResponseType (with document)
                        if (map.containsKey(responseTypeQName)) {
                            Transaction.addSchemaResponseType(transactionSchema, transaction);
                        }

                        // Add everything
                        if (map.isEmpty()) {
                            Transaction.addSchemaObjects(transactionSchema, transaction);
                        }

                        // Add c8o error objects (for internal xsd edition only)
                        ConvertigoError.updateXmlSchemaObjects(transactionSchema);

                        // Save schema to file
                        String transactionXsdFilePath = transaction.getSchemaFilePath();
                        new File(transaction.getSchemaFileDirPath()).mkdirs();
                        SchemaUtils.saveSchema(transactionXsdFilePath, transactionSchema);
                    } catch (Exception e) {
                        Engine.logDatabaseObjectManager
                                .error("[Migration 7.0.0] An error occured while migrating transaction \""
                                        + transaction.getName() + "\"", e);
                    }

                    if (transaction instanceof TransactionWithVariables) {
                        TransactionWithVariables transactionVars = (TransactionWithVariables) transaction;
                        handleRequestableVariable(transactionVars.getVariablesList());

                        // Change SQLQuery variables : i.e. {id} --> {{id}}
                        if (transaction instanceof SqlTransaction) {
                            String sqlQuery = ((SqlTransaction) transaction).getSqlQuery();

                            sqlQuery = sqlQuery.replaceAll("\\{([a-zA-Z0-9_]+)\\}", "{{$1}}");
                            ((SqlTransaction) transaction).setSqlQuery(sqlQuery);
                        }

                    }
                }
            }
        } else {// Should only happen for projects which version <= 4.6.0 
            XmlSchemaCollection collection = new XmlSchemaCollection();
            String prefix = project.getName() + "_ns";
            projectSchema = SchemaUtils.createSchema(prefix, project.getNamespaceUri(),
                    XsdForm.unqualified.name(), XsdForm.unqualified.name());
            ConvertigoError.addXmlSchemaObjects(projectSchema);
            SchemaMeta.setCollection(projectSchema, collection);

            for (Connector connector : project.getConnectorsList()) {
                for (Transaction transaction : connector.getTransactionsList()) {
                    if (transaction instanceof TransactionWithVariables) {
                        TransactionWithVariables transactionVars = (TransactionWithVariables) transaction;
                        handleRequestableVariable(transactionVars.getVariablesList());
                    }
                }
            }
        }

        // Handle sequence objects
        for (Sequence sequence : project.getSequencesList()) {
            handleSteps(projectSchema, referenceMap, sequence.getSteps());
            handleRequestableVariable(sequence.getVariablesList());
        }

        // Add all references to project
        if (!referenceMap.isEmpty()) {
            for (Reference reference : referenceMap.values())
                project.add(reference);
        }

        // Delete XSD file
        if (xsdFile.exists())
            xsdFile.delete();

        // Delete WSDL file
        if (wsdlFile.exists())
            wsdlFile.delete();

    } catch (Exception e) {
        Engine.logDatabaseObjectManager
                .error("[Migration 7.0.0] An error occured while migrating project \"" + projectName + "\"", e);
    }
}

From source file:com.evolveum.midpoint.provisioning.ucf.impl.connid.ConnectorInstanceConnIdImpl.java

private void parseResourceSchema(org.identityconnectors.framework.common.objects.Schema icfSchema,
        List<QName> generateObjectClasses) {

    AttributeInfo passwordAttributeInfo = null;
    AttributeInfo enableAttributeInfo = null;
    AttributeInfo enableDateAttributeInfo = null;
    AttributeInfo disableDateAttributeInfo = null;
    AttributeInfo lockoutAttributeInfo = null;
    AttributeInfo auxiliaryObjectClasseAttributeInfo = null;

    // New instance of midPoint schema object
    setResourceSchema(new ResourceSchemaImpl(getSchemaNamespace(), prismContext));

    if (legacySchema == null) {
        legacySchema = detectLegacySchema(icfSchema);
    }/*from   ww w .j  a  va  2s . c  o m*/
    LOGGER.trace("Converting resource schema (legacy mode: {})", legacySchema);
    LOGGER.trace("Generating object classes: {}", generateObjectClasses);

    Set<ObjectClassInfo> objectClassInfoSet = icfSchema.getObjectClassInfo();
    // Let's convert every objectclass in the ConnId schema ...
    for (ObjectClassInfo objectClassInfo : objectClassInfoSet) {

        // "Flat" ConnId object class names needs to be mapped to QNames
        QName objectClassXsdName = connIdNameMapper.objectClassToQname(
                new ObjectClass(objectClassInfo.getType()), getSchemaNamespace(), legacySchema);

        if (!shouldBeGenerated(generateObjectClasses, objectClassXsdName)) {
            LOGGER.trace("Skipping object class {} ({})", objectClassInfo.getType(), objectClassXsdName);
            continue;
        }

        LOGGER.trace("Converting object class {} ({})", objectClassInfo.getType(), objectClassXsdName);

        // ResourceObjectDefinition is a midPpoint way how to represent an
        // object class.
        // The important thing here is the last "type" parameter
        // (objectClassXsdName). The rest is more-or-less cosmetics.
        ObjectClassComplexTypeDefinition ocDef = ((ResourceSchemaImpl) resourceSchema)
                .createObjectClassDefinition(objectClassXsdName);

        // The __ACCOUNT__ objectclass in ConnId is a default account
        // objectclass. So mark it appropriately.
        if (ObjectClass.ACCOUNT_NAME.equals(objectClassInfo.getType())) {
            ((ObjectClassComplexTypeDefinitionImpl) ocDef).setKind(ShadowKindType.ACCOUNT);
            ((ObjectClassComplexTypeDefinitionImpl) ocDef).setDefaultInAKind(true);
        }

        ResourceAttributeDefinition<String> uidDefinition = null;
        ResourceAttributeDefinition<String> nameDefinition = null;
        boolean hasUidDefinition = false;

        int displayOrder = ConnectorFactoryConnIdImpl.ATTR_DISPLAY_ORDER_START;
        // Let's iterate over all attributes in this object class ...
        Set<AttributeInfo> attributeInfoSet = objectClassInfo.getAttributeInfo();
        for (AttributeInfo attributeInfo : attributeInfoSet) {
            String icfName = attributeInfo.getName();

            if (OperationalAttributes.PASSWORD_NAME.equals(icfName)) {
                // This attribute will not go into the schema
                // instead a "password" capability is used
                passwordAttributeInfo = attributeInfo;
                // Skip this attribute, capability is sufficient
                continue;
            }

            if (OperationalAttributes.ENABLE_NAME.equals(icfName)) {
                enableAttributeInfo = attributeInfo;
                // Skip this attribute, capability is sufficient
                continue;
            }

            if (OperationalAttributes.ENABLE_DATE_NAME.equals(icfName)) {
                enableDateAttributeInfo = attributeInfo;
                // Skip this attribute, capability is sufficient
                continue;
            }

            if (OperationalAttributes.DISABLE_DATE_NAME.equals(icfName)) {
                disableDateAttributeInfo = attributeInfo;
                // Skip this attribute, capability is sufficient
                continue;
            }

            if (OperationalAttributes.LOCK_OUT_NAME.equals(icfName)) {
                lockoutAttributeInfo = attributeInfo;
                // Skip this attribute, capability is sufficient
                continue;
            }

            if (PredefinedAttributes.AUXILIARY_OBJECT_CLASS_NAME.equals(icfName)) {
                auxiliaryObjectClasseAttributeInfo = attributeInfo;
                // Skip this attribute, capability is sufficient
                continue;
            }

            String processedAttributeName = icfName;
            if ((Name.NAME.equals(icfName) || Uid.NAME.equals(icfName))
                    && attributeInfo.getNativeName() != null) {
                processedAttributeName = attributeInfo.getNativeName();
            }

            QName attrXsdName = connIdNameMapper.convertAttributeNameToQName(processedAttributeName, ocDef);
            QName attrXsdType = ConnIdUtil.icfTypeToXsdType(attributeInfo.getType(), false);

            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("  attr conversion ConnId: {}({}) -> XSD: {}({})", icfName,
                        attributeInfo.getType().getSimpleName(), PrettyPrinter.prettyPrint(attrXsdName),
                        PrettyPrinter.prettyPrint(attrXsdType));
            }

            // Create ResourceObjectAttributeDefinition, which is midPoint
            // way how to express attribute schema.
            ResourceAttributeDefinitionImpl attrDef = new ResourceAttributeDefinitionImpl(attrXsdName,
                    attrXsdType, prismContext);

            attrDef.setMatchingRuleQName(icfAttributeInfoToMatchingRule(attributeInfo));

            if (Name.NAME.equals(icfName)) {
                nameDefinition = attrDef;
                if (uidDefinition != null && attrXsdName.equals(uidDefinition.getName())) {
                    attrDef.setDisplayOrder(ConnectorFactoryConnIdImpl.ICFS_UID_DISPLAY_ORDER);
                    uidDefinition = attrDef;
                    hasUidDefinition = true;
                } else {
                    if (attributeInfo.getNativeName() == null) {
                        // Set a better display name for __NAME__. The "name" is s very
                        // overloaded term, so let's try to make things
                        // a bit clearer
                        attrDef.setDisplayName(ConnectorFactoryConnIdImpl.ICFS_NAME_DISPLAY_NAME);
                    }
                    attrDef.setDisplayOrder(ConnectorFactoryConnIdImpl.ICFS_NAME_DISPLAY_ORDER);
                }

            } else if (Uid.NAME.equals(icfName)) {
                // UID can be the same as other attribute
                ResourceAttributeDefinition existingDefinition = ocDef.findAttributeDefinition(attrXsdName);
                if (existingDefinition != null) {
                    hasUidDefinition = true;
                    ((ResourceAttributeDefinitionImpl) existingDefinition)
                            .setDisplayOrder(ConnectorFactoryConnIdImpl.ICFS_UID_DISPLAY_ORDER);
                    uidDefinition = existingDefinition;
                    continue;
                } else {
                    uidDefinition = attrDef;
                    if (attributeInfo.getNativeName() == null) {
                        attrDef.setDisplayName(ConnectorFactoryConnIdImpl.ICFS_UID_DISPLAY_NAME);
                    }
                    attrDef.setDisplayOrder(ConnectorFactoryConnIdImpl.ICFS_UID_DISPLAY_ORDER);
                }

            } else {
                // Check conflict with UID definition
                if (uidDefinition != null && attrXsdName.equals(uidDefinition.getName())) {
                    attrDef.setDisplayOrder(ConnectorFactoryConnIdImpl.ICFS_UID_DISPLAY_ORDER);
                    uidDefinition = attrDef;
                    hasUidDefinition = true;
                } else {
                    attrDef.setDisplayOrder(displayOrder);
                    displayOrder += ConnectorFactoryConnIdImpl.ATTR_DISPLAY_ORDER_INCREMENT;
                }
            }

            attrDef.setNativeAttributeName(attributeInfo.getNativeName());
            attrDef.setFrameworkAttributeName(icfName);

            // Now we are going to process flags such as optional and
            // multi-valued
            Set<Flags> flagsSet = attributeInfo.getFlags();
            // System.out.println(flagsSet);

            attrDef.setMinOccurs(0);
            attrDef.setMaxOccurs(1);
            boolean canCreate = true;
            boolean canUpdate = true;
            boolean canRead = true;

            for (Flags flags : flagsSet) {
                if (flags == Flags.REQUIRED) {
                    attrDef.setMinOccurs(1);
                }
                if (flags == Flags.MULTIVALUED) {
                    attrDef.setMaxOccurs(-1);
                }
                if (flags == Flags.NOT_CREATABLE) {
                    canCreate = false;
                }
                if (flags == Flags.NOT_READABLE) {
                    canRead = false;
                }
                if (flags == Flags.NOT_UPDATEABLE) {
                    canUpdate = false;
                }
                if (flags == Flags.NOT_RETURNED_BY_DEFAULT) {
                    attrDef.setReturnedByDefault(false);
                }
            }

            attrDef.setCanAdd(canCreate);
            attrDef.setCanModify(canUpdate);
            attrDef.setCanRead(canRead);

            if (!Uid.NAME.equals(icfName)) {
                ((ObjectClassComplexTypeDefinitionImpl) ocDef).add(attrDef);
            }
        }

        if (uidDefinition == null) {
            // Every object has UID in ConnId, therefore add a default definition if no other was specified
            uidDefinition = new ResourceAttributeDefinitionImpl<>(SchemaConstants.ICFS_UID, DOMUtil.XSD_STRING,
                    prismContext);
            // DO NOT make it mandatory. It must not be present on create hence it cannot be mandatory.
            ((ResourceAttributeDefinitionImpl) uidDefinition).setMinOccurs(0);
            ((ResourceAttributeDefinitionImpl) uidDefinition).setMaxOccurs(1);
            // Make it read-only
            ((ResourceAttributeDefinitionImpl) uidDefinition).setReadOnly();
            // Set a default display name
            ((ResourceAttributeDefinitionImpl) uidDefinition)
                    .setDisplayName(ConnectorFactoryConnIdImpl.ICFS_UID_DISPLAY_NAME);
            ((ResourceAttributeDefinitionImpl) uidDefinition)
                    .setDisplayOrder(ConnectorFactoryConnIdImpl.ICFS_UID_DISPLAY_ORDER);
            // Uid is a primary identifier of every object (this is the ConnId way)
        }
        if (!hasUidDefinition) {
            ((ObjectClassComplexTypeDefinitionImpl) ocDef).add(uidDefinition);
        }
        ((ObjectClassComplexTypeDefinitionImpl) ocDef).addPrimaryIdentifier(uidDefinition);
        if (uidDefinition != nameDefinition) {
            ((ObjectClassComplexTypeDefinitionImpl) ocDef).addSecondaryIdentifier(nameDefinition);
        }

        // Add schema annotations
        ((ObjectClassComplexTypeDefinitionImpl) ocDef).setNativeObjectClass(objectClassInfo.getType());
        ((ObjectClassComplexTypeDefinitionImpl) ocDef).setDisplayNameAttribute(nameDefinition.getName());
        ((ObjectClassComplexTypeDefinitionImpl) ocDef).setNamingAttribute(nameDefinition.getName());
        ((ObjectClassComplexTypeDefinitionImpl) ocDef).setAuxiliary(objectClassInfo.isAuxiliary());

        LOGGER.trace("  ... converted object class {}: {}", objectClassInfo.getType(), ocDef);
    }

    // This is the default for all resources.
    // (Currently there is no way how to obtain it from the connector.)
    // It can be disabled manually.
    AddRemoveAttributeValuesCapabilityType addRemove = new AddRemoveAttributeValuesCapabilityType();
    capabilities.add(CAPABILITY_OBJECT_FACTORY.createAddRemoveAttributeValues(addRemove));

    ActivationCapabilityType capAct = null;

    if (enableAttributeInfo != null) {
        if (capAct == null) {
            capAct = new ActivationCapabilityType();
        }
        ActivationStatusCapabilityType capActStatus = new ActivationStatusCapabilityType();
        capAct.setStatus(capActStatus);
        if (!enableAttributeInfo.isReturnedByDefault()) {
            capActStatus.setReturnedByDefault(false);
        }
    }

    if (enableDateAttributeInfo != null) {
        if (capAct == null) {
            capAct = new ActivationCapabilityType();
        }
        ActivationValidityCapabilityType capValidFrom = new ActivationValidityCapabilityType();
        capAct.setValidFrom(capValidFrom);
        if (!enableDateAttributeInfo.isReturnedByDefault()) {
            capValidFrom.setReturnedByDefault(false);
        }
    }

    if (disableDateAttributeInfo != null) {
        if (capAct == null) {
            capAct = new ActivationCapabilityType();
        }
        ActivationValidityCapabilityType capValidTo = new ActivationValidityCapabilityType();
        capAct.setValidTo(capValidTo);
        if (!disableDateAttributeInfo.isReturnedByDefault()) {
            capValidTo.setReturnedByDefault(false);
        }
    }

    if (lockoutAttributeInfo != null) {
        if (capAct == null) {
            capAct = new ActivationCapabilityType();
        }
        ActivationLockoutStatusCapabilityType capActStatus = new ActivationLockoutStatusCapabilityType();
        capAct.setLockoutStatus(capActStatus);
        if (!lockoutAttributeInfo.isReturnedByDefault()) {
            capActStatus.setReturnedByDefault(false);
        }
    }

    if (capAct != null) {
        capabilities.add(CAPABILITY_OBJECT_FACTORY.createActivation(capAct));
    }

    if (passwordAttributeInfo != null) {
        CredentialsCapabilityType capCred = new CredentialsCapabilityType();
        PasswordCapabilityType capPass = new PasswordCapabilityType();
        if (!passwordAttributeInfo.isReturnedByDefault()) {
            capPass.setReturnedByDefault(false);
        }
        if (passwordAttributeInfo.isReadable()) {
            capPass.setReadable(true);
        }
        capCred.setPassword(capPass);
        capabilities.add(CAPABILITY_OBJECT_FACTORY.createCredentials(capCred));
    }

    if (auxiliaryObjectClasseAttributeInfo != null) {
        AuxiliaryObjectClassesCapabilityType capAux = new AuxiliaryObjectClassesCapabilityType();
        capabilities.add(CAPABILITY_OBJECT_FACTORY.createAuxiliaryObjectClasses(capAux));
    }

    boolean canPageSize = false;
    boolean canPageOffset = false;
    boolean canSort = false;
    for (OperationOptionInfo searchOption : icfSchema.getSupportedOptionsByOperation(SearchApiOp.class)) {
        switch (searchOption.getName()) {
        case OperationOptions.OP_PAGE_SIZE:
            canPageSize = true;
            break;
        case OperationOptions.OP_PAGED_RESULTS_OFFSET:
            canPageOffset = true;
            break;
        case OperationOptions.OP_SORT_KEYS:
            canSort = true;
            break;
        case OperationOptions.OP_RETURN_DEFAULT_ATTRIBUTES:
            supportsReturnDefaultAttributes = true;
            break;
        }

    }

    if (canPageSize || canPageOffset || canSort) {
        PagedSearchCapabilityType capPage = new PagedSearchCapabilityType();
        capabilities.add(CAPABILITY_OBJECT_FACTORY.createPagedSearch(capPage));
    }

}

From source file:com.evolveum.midpoint.provisioning.ucf.impl.ConnectorInstanceIcfImpl.java

private void parseResourceSchema(org.identityconnectors.framework.common.objects.Schema icfSchema,
        List<QName> generateObjectClasses) {

    AttributeInfo passwordAttributeInfo = null;
    AttributeInfo enableAttributeInfo = null;
    AttributeInfo enableDateAttributeInfo = null;
    AttributeInfo disableDateAttributeInfo = null;
    AttributeInfo lockoutAttributeInfo = null;
    AttributeInfo auxiliaryObjectClasseAttributeInfo = null;

    // New instance of midPoint schema object
    setResourceSchema(new ResourceSchema(getSchemaNamespace(), prismContext));

    if (legacySchema == null) {
        legacySchema = detectLegacySchema(icfSchema);
    }// www  .  j ava2 s.  c om
    LOGGER.trace("Converting resource schema (legacy mode: {})", legacySchema);

    Set<ObjectClassInfo> objectClassInfoSet = icfSchema.getObjectClassInfo();
    // Let's convert every objectclass in the ICF schema ...      
    for (ObjectClassInfo objectClassInfo : objectClassInfoSet) {

        // "Flat" ICF object class names needs to be mapped to QNames
        QName objectClassXsdName = icfNameMapper.objectClassToQname(new ObjectClass(objectClassInfo.getType()),
                getSchemaNamespace(), legacySchema);

        if (!shouldBeGenerated(generateObjectClasses, objectClassXsdName)) {
            LOGGER.trace("Skipping object class {} ({})", objectClassInfo.getType(), objectClassXsdName);
            continue;
        }

        LOGGER.trace("Convering object class {} ({})", objectClassInfo.getType(), objectClassXsdName);

        // ResourceObjectDefinition is a midPpoint way how to represent an
        // object class.
        // The important thing here is the last "type" parameter
        // (objectClassXsdName). The rest is more-or-less cosmetics.
        ObjectClassComplexTypeDefinition ocDef = resourceSchema.createObjectClassDefinition(objectClassXsdName);

        // The __ACCOUNT__ objectclass in ICF is a default account
        // objectclass. So mark it appropriately.
        if (ObjectClass.ACCOUNT_NAME.equals(objectClassInfo.getType())) {
            ocDef.setKind(ShadowKindType.ACCOUNT);
            ocDef.setDefaultInAKind(true);
        }

        ResourceAttributeDefinition<String> uidDefinition = null;
        ResourceAttributeDefinition<String> nameDefinition = null;
        boolean hasUidDefinition = false;

        int displayOrder = ConnectorFactoryIcfImpl.ATTR_DISPLAY_ORDER_START;
        // Let's iterate over all attributes in this object class ...
        Set<AttributeInfo> attributeInfoSet = objectClassInfo.getAttributeInfo();
        for (AttributeInfo attributeInfo : attributeInfoSet) {
            String icfName = attributeInfo.getName();

            if (OperationalAttributes.PASSWORD_NAME.equals(icfName)) {
                // This attribute will not go into the schema
                // instead a "password" capability is used
                passwordAttributeInfo = attributeInfo;
                // Skip this attribute, capability is sufficient
                continue;
            }

            if (OperationalAttributes.ENABLE_NAME.equals(icfName)) {
                enableAttributeInfo = attributeInfo;
                // Skip this attribute, capability is sufficient
                continue;
            }

            if (OperationalAttributes.ENABLE_DATE_NAME.equals(icfName)) {
                enableDateAttributeInfo = attributeInfo;
                // Skip this attribute, capability is sufficient
                continue;
            }

            if (OperationalAttributes.DISABLE_DATE_NAME.equals(icfName)) {
                disableDateAttributeInfo = attributeInfo;
                // Skip this attribute, capability is sufficient
                continue;
            }

            if (OperationalAttributes.LOCK_OUT_NAME.equals(icfName)) {
                lockoutAttributeInfo = attributeInfo;
                // Skip this attribute, capability is sufficient
                continue;
            }

            if (PredefinedAttributes.AUXILIARY_OBJECT_CLASS_NAME.equals(icfName)) {
                auxiliaryObjectClasseAttributeInfo = attributeInfo;
                // Skip this attribute, capability is sufficient
                continue;
            }

            String processedAttributeName = icfName;
            if ((Name.NAME.equals(icfName) || Uid.NAME.equals(icfName))
                    && attributeInfo.getNativeName() != null) {
                processedAttributeName = attributeInfo.getNativeName();
            }

            QName attrXsdName = icfNameMapper.convertAttributeNameToQName(processedAttributeName, ocDef);
            QName attrXsdType = icfTypeToXsdType(attributeInfo.getType(), false);

            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Attr conversion ICF: {}({}) -> XSD: {}({})",
                        new Object[] { icfName, attributeInfo.getType().getSimpleName(),
                                PrettyPrinter.prettyPrint(attrXsdName),
                                PrettyPrinter.prettyPrint(attrXsdType) });
            }

            // Create ResourceObjectAttributeDefinition, which is midPoint
            // way how to express attribute schema.
            ResourceAttributeDefinition attrDef = new ResourceAttributeDefinition(attrXsdName, attrXsdType,
                    prismContext);

            if (Name.NAME.equals(icfName)) {
                nameDefinition = attrDef;
                if (uidDefinition != null && attrXsdName.equals(uidDefinition.getName())) {
                    attrDef.setDisplayOrder(ConnectorFactoryIcfImpl.ICFS_UID_DISPLAY_ORDER);
                    uidDefinition = attrDef;
                    hasUidDefinition = true;
                } else {
                    if (attributeInfo.getNativeName() == null) {
                        // Set a better display name for __NAME__. The "name" is s very
                        // overloaded term, so let's try to make things
                        // a bit clearer
                        attrDef.setDisplayName(ConnectorFactoryIcfImpl.ICFS_NAME_DISPLAY_NAME);
                    }
                    attrDef.setDisplayOrder(ConnectorFactoryIcfImpl.ICFS_NAME_DISPLAY_ORDER);
                }

            } else if (Uid.NAME.equals(icfName)) {
                // UID can be the same as other attribute
                ResourceAttributeDefinition existingDefinition = ocDef.findAttributeDefinition(attrXsdName);
                if (existingDefinition != null) {
                    hasUidDefinition = true;
                    existingDefinition.setDisplayOrder(ConnectorFactoryIcfImpl.ICFS_UID_DISPLAY_ORDER);
                    uidDefinition = existingDefinition;
                    continue;
                } else {
                    uidDefinition = attrDef;
                    if (attributeInfo.getNativeName() == null) {
                        attrDef.setDisplayName(ConnectorFactoryIcfImpl.ICFS_UID_DISPLAY_NAME);
                    }
                    attrDef.setDisplayOrder(ConnectorFactoryIcfImpl.ICFS_UID_DISPLAY_ORDER);
                }

            } else {
                // Check conflict with UID definition
                if (uidDefinition != null && attrXsdName.equals(uidDefinition.getName())) {
                    attrDef.setDisplayOrder(ConnectorFactoryIcfImpl.ICFS_UID_DISPLAY_ORDER);
                    uidDefinition = attrDef;
                    hasUidDefinition = true;
                } else {
                    attrDef.setDisplayOrder(displayOrder);
                    displayOrder += ConnectorFactoryIcfImpl.ATTR_DISPLAY_ORDER_INCREMENT;
                }
            }

            attrDef.setNativeAttributeName(attributeInfo.getNativeName());
            attrDef.setFrameworkAttributeName(icfName);

            // Now we are going to process flags such as optional and
            // multi-valued
            Set<Flags> flagsSet = attributeInfo.getFlags();
            // System.out.println(flagsSet);

            attrDef.setMinOccurs(0);
            attrDef.setMaxOccurs(1);
            boolean canCreate = true;
            boolean canUpdate = true;
            boolean canRead = true;

            for (Flags flags : flagsSet) {
                if (flags == Flags.REQUIRED) {
                    attrDef.setMinOccurs(1);
                }
                if (flags == Flags.MULTIVALUED) {
                    attrDef.setMaxOccurs(-1);
                }
                if (flags == Flags.NOT_CREATABLE) {
                    canCreate = false;
                }
                if (flags == Flags.NOT_READABLE) {
                    canRead = false;
                }
                if (flags == Flags.NOT_UPDATEABLE) {
                    canUpdate = false;
                }
                if (flags == Flags.NOT_RETURNED_BY_DEFAULT) {
                    attrDef.setReturnedByDefault(false);
                }
            }

            attrDef.setCanAdd(canCreate);
            attrDef.setCanModify(canUpdate);
            attrDef.setCanRead(canRead);

            if (!Uid.NAME.equals(icfName)) {
                ocDef.add(attrDef);
            }
        }

        if (uidDefinition == null) {
            // Every object has UID in ICF, therefore add a default definition if no other was specified
            uidDefinition = new ResourceAttributeDefinition<String>(ConnectorFactoryIcfImpl.ICFS_UID,
                    DOMUtil.XSD_STRING, prismContext);
            // DO NOT make it mandatory. It must not be present on create hence it cannot be mandatory.
            uidDefinition.setMinOccurs(0);
            uidDefinition.setMaxOccurs(1);
            // Make it read-only
            uidDefinition.setReadOnly();
            // Set a default display name
            uidDefinition.setDisplayName(ConnectorFactoryIcfImpl.ICFS_UID_DISPLAY_NAME);
            uidDefinition.setDisplayOrder(ConnectorFactoryIcfImpl.ICFS_UID_DISPLAY_ORDER);
            // Uid is a primary identifier of every object (this is the ICF way)
        }
        if (!hasUidDefinition) {
            ocDef.add(uidDefinition);
        }
        ((Collection<ResourceAttributeDefinition>) ocDef.getIdentifiers()).add(uidDefinition);
        if (uidDefinition != nameDefinition) {
            ((Collection<ResourceAttributeDefinition>) ocDef.getSecondaryIdentifiers()).add(nameDefinition);
        }

        // Add schema annotations
        ocDef.setNativeObjectClass(objectClassInfo.getType());
        ocDef.setDisplayNameAttribute(nameDefinition.getName());
        ocDef.setNamingAttribute(nameDefinition.getName());
        ocDef.setAuxiliary(objectClassInfo.isAuxiliary());

    }

    capabilities = new ArrayList<>();

    // This is the default for all resources.
    // (Currently there is no way how to obtain it from the connector.)
    // It can be disabled manually.
    AddRemoveAttributeValuesCapabilityType addRemove = new AddRemoveAttributeValuesCapabilityType();
    capabilities.add(capabilityObjectFactory.createAddRemoveAttributeValues(addRemove));

    ActivationCapabilityType capAct = null;

    if (enableAttributeInfo != null) {
        if (capAct == null) {
            capAct = new ActivationCapabilityType();
        }
        ActivationStatusCapabilityType capActStatus = new ActivationStatusCapabilityType();
        capAct.setStatus(capActStatus);
        if (!enableAttributeInfo.isReturnedByDefault()) {
            capActStatus.setReturnedByDefault(false);
        }
    }

    if (enableDateAttributeInfo != null) {
        if (capAct == null) {
            capAct = new ActivationCapabilityType();
        }
        ActivationValidityCapabilityType capValidFrom = new ActivationValidityCapabilityType();
        capAct.setValidFrom(capValidFrom);
        if (!enableDateAttributeInfo.isReturnedByDefault()) {
            capValidFrom.setReturnedByDefault(false);
        }
    }

    if (disableDateAttributeInfo != null) {
        if (capAct == null) {
            capAct = new ActivationCapabilityType();
        }
        ActivationValidityCapabilityType capValidTo = new ActivationValidityCapabilityType();
        capAct.setValidTo(capValidTo);
        if (!disableDateAttributeInfo.isReturnedByDefault()) {
            capValidTo.setReturnedByDefault(false);
        }
    }

    if (lockoutAttributeInfo != null) {
        if (capAct == null) {
            capAct = new ActivationCapabilityType();
        }
        ActivationLockoutStatusCapabilityType capActStatus = new ActivationLockoutStatusCapabilityType();
        capAct.setLockoutStatus(capActStatus);
        if (!lockoutAttributeInfo.isReturnedByDefault()) {
            capActStatus.setReturnedByDefault(false);
        }
    }

    if (capAct != null) {
        capabilities.add(capabilityObjectFactory.createActivation(capAct));
    }

    if (passwordAttributeInfo != null) {
        CredentialsCapabilityType capCred = new CredentialsCapabilityType();
        PasswordCapabilityType capPass = new PasswordCapabilityType();
        if (!passwordAttributeInfo.isReturnedByDefault()) {
            capPass.setReturnedByDefault(false);
        }
        capCred.setPassword(capPass);
        capabilities.add(capabilityObjectFactory.createCredentials(capCred));
    }

    if (auxiliaryObjectClasseAttributeInfo != null) {
        AuxiliaryObjectClassesCapabilityType capAux = new AuxiliaryObjectClassesCapabilityType();
        capabilities.add(capabilityObjectFactory.createAuxiliaryObjectClasses(capAux));
    }

    // Create capabilities from supported connector operations

    InternalMonitor.recordConnectorOperation("getSupportedOperations");
    Set<Class<? extends APIOperation>> supportedOperations = icfConnectorFacade.getSupportedOperations();

    LOGGER.trace("Connector supported operations: {}", supportedOperations);

    if (supportedOperations.contains(SyncApiOp.class)) {
        LiveSyncCapabilityType capSync = new LiveSyncCapabilityType();
        capabilities.add(capabilityObjectFactory.createLiveSync(capSync));
    }

    if (supportedOperations.contains(TestApiOp.class)) {
        TestConnectionCapabilityType capTest = new TestConnectionCapabilityType();
        capabilities.add(capabilityObjectFactory.createTestConnection(capTest));
    }

    if (supportedOperations.contains(CreateApiOp.class)) {
        CreateCapabilityType capCreate = new CreateCapabilityType();
        capabilities.add(capabilityObjectFactory.createCreate(capCreate));
    }

    if (supportedOperations.contains(GetApiOp.class) || supportedOperations.contains(SearchApiOp.class)) {
        ReadCapabilityType capRead = new ReadCapabilityType();
        capabilities.add(capabilityObjectFactory.createRead(capRead));
    }

    if (supportedOperations.contains(UpdateApiOp.class)) {
        UpdateCapabilityType capUpdate = new UpdateCapabilityType();
        capabilities.add(capabilityObjectFactory.createUpdate(capUpdate));
    }

    if (supportedOperations.contains(DeleteApiOp.class)) {
        DeleteCapabilityType capDelete = new DeleteCapabilityType();
        capabilities.add(capabilityObjectFactory.createDelete(capDelete));
    }

    if (supportedOperations.contains(ScriptOnResourceApiOp.class)
            || supportedOperations.contains(ScriptOnConnectorApiOp.class)) {
        ScriptCapabilityType capScript = new ScriptCapabilityType();
        if (supportedOperations.contains(ScriptOnResourceApiOp.class)) {
            Host host = new Host();
            host.setType(ProvisioningScriptHostType.RESOURCE);
            capScript.getHost().add(host);
            // language is unknown here
        }
        if (supportedOperations.contains(ScriptOnConnectorApiOp.class)) {
            Host host = new Host();
            host.setType(ProvisioningScriptHostType.CONNECTOR);
            capScript.getHost().add(host);
            // language is unknown here
        }
        capabilities.add(capabilityObjectFactory.createScript(capScript));
    }

    boolean canPageSize = false;
    boolean canPageOffset = false;
    boolean canSort = false;
    for (OperationOptionInfo searchOption : icfSchema.getSupportedOptionsByOperation(SearchApiOp.class)) {
        switch (searchOption.getName()) {
        case OperationOptions.OP_PAGE_SIZE:
            canPageSize = true;
            break;
        case OperationOptions.OP_PAGED_RESULTS_OFFSET:
            canPageOffset = true;
            break;
        case OperationOptions.OP_SORT_KEYS:
            canSort = true;
            break;
        case OperationOptions.OP_RETURN_DEFAULT_ATTRIBUTES:
            supportsReturnDefaultAttributes = true;
            break;
        }

    }

    if (canPageSize || canPageOffset || canSort) {
        PagedSearchCapabilityType capPage = new PagedSearchCapabilityType();
        capabilities.add(capabilityObjectFactory.createPagedSearch(capPage));
    }

}

From source file:com.evolveum.midpoint.model.impl.lens.projector.focus.InboundProcessor.java

private <V extends PrismValue, D extends ItemDefinition, F extends FocusType> boolean processAssociationInbound(
        QName accountAttributeName, ObjectDelta<ShadowType> aPrioriProjectionDelta,
        final LensProjectionContext projContext, RefinedObjectClassDefinition projectionDefinition,
        final LensContext<F> context, XMLGregorianCalendar now,
        Map<ItemDefinition, List<MappingImpl<?, ?>>> mappingsToTarget, Task task, OperationResult result)
        throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, ConfigurationException,
        SecurityViolationException, CommunicationException {

    PrismObject<ShadowType> projCurrent = projContext.getObjectCurrent();
    PrismObject<ShadowType> projNew = projContext.getObjectNew();

    final ItemDelta<V, D> attributeAPrioriDelta;
    if (aPrioriProjectionDelta != null) {
        attributeAPrioriDelta = aPrioriProjectionDelta.findItemDelta(new ItemPath(ShadowType.F_ASSOCIATION));
        if (attributeAPrioriDelta == null && !projContext.isFullShadow()
                && !LensUtil.hasDependentContext(context, projContext)) {
            LOGGER.trace(/*from w  w  w .  ja v  a  2  s  . com*/
                    "Skipping inbound for {} in {}: Not a full shadow and account a priori delta exists, but doesn't have change for processed property.",
                    accountAttributeName, projContext.getResourceShadowDiscriminator());
            return true;
        }
    } else {
        attributeAPrioriDelta = null;
    }

    RefinedAssociationDefinition associationDef = projectionDefinition
            .findAssociationDefinition(accountAttributeName);

    //TODO:
    if (associationDef.isIgnored(LayerType.MODEL)) {
        LOGGER.trace("Skipping inbound for association {} in {} because the association is ignored",
                PrettyPrinter.prettyPrint(accountAttributeName), projContext.getResourceShadowDiscriminator());
        return true;
    }

    List<MappingType> inboundMappingTypes = associationDef.getInboundMappingTypes();
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Processing inbound for {} in {}; ({} mappings)",
                PrettyPrinter.prettyPrint(accountAttributeName), projContext.getResourceShadowDiscriminator(),
                inboundMappingTypes.size());
    }

    PropertyLimitations limitations = associationDef.getLimitations(LayerType.MODEL);
    if (limitations != null) {
        PropertyAccessType access = limitations.getAccess();
        if (access != null) {
            if (access.isRead() == null || !access.isRead()) {
                LOGGER.warn("Inbound mapping for non-readable association {} in {}, skipping",
                        accountAttributeName, projContext.getHumanReadableName());
                return true;
            }
        }
    }

    if (inboundMappingTypes.isEmpty()) {
        return true;
    }

    for (MappingType inboundMappingType : inboundMappingTypes) {

        // There are two processing options:
        //
        //  * If we have a delta as an input we will proceed in relative mode, applying mappings on the delta.
        //    This usually happens when a delta comes from a sync notification or if there is a primary projection delta.
        //
        //  * if we do NOT have a delta then we will proceed in absolute mode. In that mode we will apply the
        //    mappings to the absolute projection state that we got from provisioning. This is a kind of "inbound reconciliation".
        //
        // TODO what if there is a priori delta for a given attribute (e.g. ADD one) and
        // we want to reconcile also the existing attribute value? This probably would not work.
        if (inboundMappingType.getStrength() == MappingStrengthType.STRONG) {
            LOGGER.trace(
                    "There is an association inbound mapping with strength == STRONG, trying to load full account now.");
            if (!projContext.isFullShadow() && !projContext.isDelete()) {
                projCurrent = loadProjection(context, projContext, task, result, projCurrent);
                if (projContext.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.BROKEN) {
                    return false;
                }
            }
        }

        if (attributeAPrioriDelta == null && !projContext.isFullShadow()
                && !LensUtil.hasDependentContext(context, projContext)) {
            LOGGER.trace(
                    "Skipping association inbound for {} in {}: Not a full shadow and account a priori delta exists, but doesn't have change for processed property.",
                    accountAttributeName, projContext.getResourceShadowDiscriminator());
            continue;
        }

        PrismObject<F> focus;
        if (context.getFocusContext().getObjectCurrent() != null) {
            focus = context.getFocusContext().getObjectCurrent();
        } else {
            focus = context.getFocusContext().getObjectNew();
        }

        ItemDelta focusItemDelta = null;
        if (attributeAPrioriDelta != null) {
            LOGGER.trace("Processing association inbound from a priori delta: {}", attributeAPrioriDelta);

            PrismContainer<ShadowAssociationType> oldShadowAssociation = projCurrent
                    .findContainer(ShadowType.F_ASSOCIATION);

            PrismContainer<ShadowAssociationType> filteredAssociations = null;
            if (oldShadowAssociation != null) {
                filteredAssociations = oldShadowAssociation.getDefinition().instantiate();
                Collection<PrismContainerValue<ShadowAssociationType>> filteredAssociationValues = oldShadowAssociation
                        .getValues().stream()
                        .filter(rVal -> accountAttributeName.equals(rVal.asContainerable().getName()))
                        .map(val -> val.clone()).collect(Collectors.toCollection(ArrayList::new));
                prismContext.adopt(filteredAssociations);
                filteredAssociations.addAll(filteredAssociationValues);
            }

            resolveEntitlementsIfNeeded((ContainerDelta<ShadowAssociationType>) attributeAPrioriDelta,
                    filteredAssociations, projContext, task, result);

            VariableProducer<PrismContainerValue<ShadowAssociationType>> entitlementVariable = (value,
                    variables) -> resolveEntitlement(value, projContext, variables);
            collectMappingsForTargets(context, projContext, inboundMappingType, accountAttributeName,
                    (Item) oldShadowAssociation, attributeAPrioriDelta, focus,
                    (VariableProducer) entitlementVariable, mappingsToTarget, task, result);

        } else if (projCurrent != null) {

            projCurrent = loadFullShadowIfNeeded(projContext, projCurrent, context, now, task, result);
            if (projCurrent == null) {
                LOGGER.trace("Loading of full shadow failed");
                return false;
            }

            PrismContainer<ShadowAssociationType> oldShadowAssociation = projCurrent
                    .findContainer(ShadowType.F_ASSOCIATION);

            if (oldShadowAssociation == null) {
                LOGGER.trace("No shadow association value");
                return true;
            }

            PrismContainer<ShadowAssociationType> filteredAssociations = oldShadowAssociation.getDefinition()
                    .instantiate();
            Collection<PrismContainerValue<ShadowAssociationType>> filteredAssociationValues = oldShadowAssociation
                    .getValues().stream()
                    .filter(rVal -> accountAttributeName.equals(rVal.asContainerable().getName()))
                    .map(val -> val.clone()).collect(Collectors.toCollection(ArrayList::new));
            prismContext.adopt(filteredAssociations);
            filteredAssociations.addAll(filteredAssociationValues);

            resolveEntitlementsIfNeeded((ContainerDelta<ShadowAssociationType>) attributeAPrioriDelta,
                    filteredAssociations, projContext, task, result);

            VariableProducer<PrismContainerValue<ShadowAssociationType>> entitlementVariable = (value,
                    variables) -> resolveEntitlement(value, projContext, variables);
            ;

            LOGGER.trace("Processing association inbound from account sync absolute state (currentAccount): {}",
                    filteredAssociations);
            collectMappingsForTargets(context, projContext, inboundMappingType, accountAttributeName,
                    filteredAssociations, null, focus, entitlementVariable, mappingsToTarget, task, result);

        }
    }

    return true;
}

From source file:nl.denhaag.tw.comparators.schema.ElementComparator.java

private Element getGlobalElement(Element element) {
    QName ref = element.getRef();
    if (ref != null) {
        ElementImpl elementImpl = (ElementImpl) element;
        AbsItfSchema schema = elementImpl.getSchema();
        List<Element> globalElements = schema.findElementsInAllSchema(ref);
        for (Element globalElement : globalElements) {
            if (ref.equals(globalElement.getQName())) {
                return element;
            }/*from   ww w .j  a  v a 2 s.c  om*/
        }
    }
    return null;
}

From source file:org.apache.airavata.client.stub.interpretor.WorkflowInterpretorStub.java

private boolean optimizeContent(javax.xml.namespace.QName opName) {

    if (opNameArray == null) {
        return false;
    }/*ww  w.  j av  a  2 s. com*/
    for (int i = 0; i < opNameArray.length; i++) {
        if (opName.equals(opNameArray[i])) {
            return true;
        }
    }
    return false;
}

From source file:org.apache.axiom.om.util.OMXMLStreamReaderValidator.java

public int next() throws XMLStreamException {
    int event = delegate.next();
    logParserState();/*  ww  w.j  av a2  s. c  om*/

    // Make sure that the start element and end element events match.
    // Mismatched events are a key indication that the delegate stream reader is 
    // broken or corrupted.
    switch (event) {
    case XMLStreamConstants.START_ELEMENT:
        stack.push(delegate.getName());
        break;
    case XMLStreamConstants.END_ELEMENT:
        QName delegateQName = delegate.getName();
        if (stack.isEmpty()) {
            reportMismatchedEndElement(null, delegateQName);
        } else {
            QName expectedQName = (QName) stack.pop();

            if (!expectedQName.equals(delegateQName)) {
                reportMismatchedEndElement(expectedQName, delegateQName);
            }
        }
        break;

    default:

    }

    return event;
}

From source file:org.apache.axiom.util.stax.debug.XMLStreamReaderValidator.java

private void trackEvent(int event) throws XMLStreamException {
    logParserState();//from  w  w  w  .j  a  va  2  s . c o m

    // Make sure that the start element and end element events match.
    // Mismatched events are a key indication that the delegate stream reader is 
    // broken or corrupted.
    switch (event) {
    case XMLStreamConstants.START_ELEMENT:
        stack.push(super.getName());
        break;
    case XMLStreamConstants.END_ELEMENT:
        QName delegateQName = super.getName();
        if (stack.isEmpty()) {
            reportMismatchedEndElement(null, delegateQName);
        } else {
            QName expectedQName = (QName) stack.pop();

            if (!expectedQName.equals(delegateQName)) {
                reportMismatchedEndElement(expectedQName, delegateQName);
            }
        }
        break;

    default:

    }
}

From source file:org.apache.axis.client.Call.java

/** Invoke an RPC service with a pre-constructed RPCElement.
 *
 * Note: Not part of JAX-RPC specification.
 *
 * @param body an RPCElement containing all the information about
 *             this call.//from ww  w .jav  a  2s  .c  om
 * @return a deserialized Java Object containing the return value
 * @exception AxisFault
 */
public Object invoke(RPCElement body) throws AxisFault {
    if (log.isDebugEnabled()) {
        log.debug("Enter: Call::invoke(RPCElement)");
    }

    /**
     * Since JAX-RPC requires us to specify a return type if we've set
     * parameter types, check for this case right now and toss a fault
     * if things don't look right.
     */
    if (!invokeOneWay && operation != null && operation.getNumParams() > 0 && getReturnType() == null) {
        // TCK:
        // Issue an error if the return type was not set, but continue processing.
        //throw new AxisFault(Messages.getMessage("mustSpecifyReturnType"));
        log.error(Messages.getMessage("mustSpecifyReturnType"));
    }

    SOAPEnvelope reqEnv = new SOAPEnvelope(msgContext.getSOAPConstants(), msgContext.getSchemaVersion());
    SOAPEnvelope resEnv = null;
    Message reqMsg = new Message(reqEnv);
    Message resMsg = null;
    Vector resArgs = null;
    Object result = null;

    // Clear the output params
    outParams = new HashMap();
    outParamsList = new ArrayList();

    // Set both the envelope and the RPCElement encoding styles
    try {
        body.setEncodingStyle(getEncodingStyle());

        setRequestMessage(reqMsg);

        reqEnv.addBodyElement(body);
        reqEnv.setMessageType(Message.REQUEST);

        invoke();
    } catch (Exception e) {
        entLog.debug(Messages.getMessage("toAxisFault00"), e);
        throw AxisFault.makeFault(e);
    }

    resMsg = msgContext.getResponseMessage();

    if (resMsg == null) {
        if (msgContext.isPropertyTrue(FAULT_ON_NO_RESPONSE, false)) {
            throw new AxisFault(Messages.getMessage("nullResponse00"));
        } else {
            return null;
        }
    }

    resEnv = resMsg.getSOAPEnvelope();
    SOAPBodyElement bodyEl = resEnv.getFirstBody();
    if (bodyEl == null) {
        return null;
    }

    if (bodyEl instanceof RPCElement) {
        try {
            resArgs = ((RPCElement) bodyEl).getParams();
        } catch (Exception e) {
            log.error(Messages.getMessage("exception00"), e);
            throw AxisFault.makeFault(e);
        }

        if (resArgs != null && resArgs.size() > 0) {

            // If there is no return, then we start at index 0 to create the outParams Map.
            // If there IS a return, then we start with 1.
            int outParamStart = 0;

            // If we have resArgs and the returnType is specified, then the first
            // resArgs is the return.  If we have resArgs and neither returnType
            // nor paramXMLTypes are specified, then we assume that the caller is
            // following the non-JAX-RPC AXIS shortcut of not having to specify
            // the return, in which case we again assume the first resArgs is
            // the return.
            // NOTE 1:  the non-JAX-RPC AXIS shortcut allows a potential error
            // to escape notice.  If the caller IS NOT following the non-JAX-RPC
            // shortcut but instead intentionally leaves returnType and params
            // null (ie., a method that takes no parameters and returns nothing)
            // then, if we DO receive something it should be an error, but this
            // code passes it through.  The ideal solution here is to require
            // this caller to set the returnType to void, but there's no void
            // type in XML.
            // NOTE 2:  we should probably verify that the resArgs element
            // types match the expected returnType and paramXMLTypes, but I'm not
            // sure how to do that since the resArgs value is a Java Object
            // and the returnType and paramXMLTypes are QNames.

            // GD 03/15/02 : We're now checking for invalid metadata
            // config at the top of this method, so don't need to do it
            // here.  Check for void return, though.

            boolean findReturnParam = false;
            QName returnParamQName = null;
            if (operation != null) {
                returnParamQName = operation.getReturnQName();
            }

            if (!XMLType.AXIS_VOID.equals(getReturnType())) {
                if (returnParamQName == null) {
                    // Assume the first param is the return
                    RPCParam param = (RPCParam) resArgs.get(0);
                    result = param.getObjectValue();
                    outParamStart = 1;
                } else {
                    // If the QName of the return value was given to us, look
                    // through the result arguments to find the right name
                    findReturnParam = true;
                }
            }

            // The following loop looks at the resargs and
            // converts the value to the appropriate return/out parameter
            // value.  If the return value is found, is value is
            // placed in result.  The remaining resargs are
            // placed in the outParams list (note that if a resArg
            // is found that does not match a operation parameter qname,
            // it is still placed in the outParms list).
            for (int i = outParamStart; i < resArgs.size(); i++) {
                RPCParam param = (RPCParam) resArgs.get(i);

                Class javaType = getJavaTypeForQName(param.getQName());
                Object value = param.getObjectValue();

                // Convert type if needed
                if (javaType != null && value != null && !javaType.isAssignableFrom(value.getClass())) {
                    value = JavaUtils.convert(value, javaType);
                }

                // Check if this parameter is our return
                // otherwise just add it to our outputs
                if (findReturnParam && returnParamQName.equals(param.getQName())) {
                    // found it!
                    result = value;
                    findReturnParam = false;
                } else {
                    outParams.put(param.getQName(), value);
                    outParamsList.add(value);
                }
            }

            // added by scheu:
            // If the return param is still not found, that means
            // the returned value did not have the expected qname.
            // The soap specification indicates that this should be
            // accepted (and we also fail interop tests if we are strict here).
            // Look through the outParms and find one that
            // does not match one of the operation parameters.
            if (findReturnParam) {
                Iterator it = outParams.keySet().iterator();
                while (findReturnParam && it.hasNext()) {
                    QName qname = (QName) it.next();
                    ParameterDesc paramDesc = operation.getOutputParamByQName(qname);
                    if (paramDesc == null) {
                        // Doesn't match a paramter, so use this for the return
                        findReturnParam = false;
                        result = outParams.remove(qname);
                    }
                }
            }

            // If we were looking for a particular QName for the return and
            // still didn't find it, throw an exception
            if (findReturnParam) {
                String returnParamName = returnParamQName.toString();
                throw new AxisFault(Messages.getMessage("noReturnParam", returnParamName));
            }
        }
    } else {
        // This is a SOAPBodyElement, try to treat it like a return value
        try {
            result = bodyEl.getValueAsType(getReturnType());
        } catch (Exception e) {
            // just return the SOAPElement
            result = bodyEl;
        }

    }

    if (log.isDebugEnabled()) {
        log.debug("Exit: Call::invoke(RPCElement)");
    }

    // Convert type if needed
    if (operation != null && operation.getReturnClass() != null) {
        result = JavaUtils.convert(result, operation.getReturnClass());
    }

    return (result);
}