Search in sources :

Example 56 with Tag

use of org.wso2.carbon.registry.core.Tag in project carbon-apimgt by wso2.

the class APIUtil method getAPIProduct.

/**
 * Retrieves api product artifact from registry
 *
 * @param artifact
 * @param registry
 * @return APIProduct
 * @throws org.wso2.carbon.apimgt.api.APIManagementException
 */
public static APIProduct getAPIProduct(GovernanceArtifact artifact, Registry registry) throws APIManagementException {
    APIProduct apiProduct;
    try {
        String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
        String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
        String productName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
        String productVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
        APIProductIdentifier apiProductIdentifier = new APIProductIdentifier(providerName, productName, productVersion);
        apiProductIdentifier.setUUID(artifact.getId());
        apiProduct = new APIProduct(apiProductIdentifier);
        apiProduct.setUuid(artifact.getId());
        apiProduct.setRating(Float.toString(getAverageRating(artifact.getId())));
        ApiMgtDAO.getInstance().setAPIProductFromDB(apiProduct);
        setResourceProperties(apiProduct, registry, artifactPath);
        // set uuid
        apiProduct.setUuid(artifact.getId());
        apiProduct.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT));
        apiProduct.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
        apiProduct.setState(getLcStateFromArtifact(artifact));
        apiProduct.setThumbnailUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
        apiProduct.setVisibility(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY));
        apiProduct.setVisibleRoles(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES));
        apiProduct.setVisibleTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS));
        apiProduct.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER));
        apiProduct.setBusinessOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL));
        apiProduct.setTechnicalOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER));
        apiProduct.setTechnicalOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL));
        apiProduct.setSubscriptionAvailability(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY));
        apiProduct.setSubscriptionAvailableTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS));
        String environments = artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS);
        apiProduct.setEnvironments(extractEnvironmentsForAPI(environments));
        apiProduct.setTransports(artifact.getAttribute(APIConstants.API_OVERVIEW_TRANSPORTS));
        apiProduct.setApiSecurity(artifact.getAttribute(APIConstants.API_OVERVIEW_API_SECURITY));
        apiProduct.setAuthorizationHeader(artifact.getAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER));
        apiProduct.setCorsConfiguration(getCorsConfigurationFromArtifact(artifact));
        apiProduct.setCreatedTime(registry.get(artifactPath).getCreatedTime());
        apiProduct.setLastUpdated(registry.get(artifactPath).getLastModified());
        apiProduct.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
        apiProduct.setGatewayVendor(artifact.getAttribute(APIConstants.API_GATEWAY_VENDOR));
        String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(providerName));
        apiProduct.setTenantDomain(tenantDomainName);
        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomainName);
        String tiers = artifact.getAttribute(APIConstants.API_OVERVIEW_TIER);
        Map<String, Tier> definedTiers = getTiers(tenantId);
        Set<Tier> availableTier = getAvailableTiers(definedTiers, tiers, productName);
        apiProduct.setAvailableTiers(availableTier);
        // We set the context template here
        apiProduct.setContextTemplate(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
        apiProduct.setEnableSchemaValidation(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENABLE_JSON_SCHEMA)));
        apiProduct.setEnableStore(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENABLE_STORE)));
        apiProduct.setTestKey(artifact.getAttribute(APIConstants.API_OVERVIEW_TESTKEY));
        apiProduct.setResponseCache(artifact.getAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING));
        int cacheTimeout = APIConstants.API_RESPONSE_CACHE_TIMEOUT;
        try {
            cacheTimeout = Integer.parseInt(artifact.getAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT));
        } catch (NumberFormatException e) {
            if (log.isDebugEnabled()) {
                log.debug("Error in converting cache time out due to " + e.getMessage());
            }
        }
        apiProduct.setCacheTimeout(cacheTimeout);
        List<APIProductResource> resources = ApiMgtDAO.getInstance().getAPIProductResourceMappings(apiProductIdentifier);
        Map<String, Scope> uniqueAPIProductScopeKeyMappings = new LinkedHashMap<>();
        for (APIProductResource resource : resources) {
            List<Scope> resourceScopes = resource.getUriTemplate().retrieveAllScopes();
            ListIterator it = resourceScopes.listIterator();
            while (it.hasNext()) {
                Scope resourceScope = (Scope) it.next();
                String scopeKey = resourceScope.getKey();
                if (!uniqueAPIProductScopeKeyMappings.containsKey(scopeKey)) {
                    resourceScope = getScopeByName(scopeKey, tenantDomainName);
                    uniqueAPIProductScopeKeyMappings.put(scopeKey, resourceScope);
                } else {
                    resourceScope = uniqueAPIProductScopeKeyMappings.get(scopeKey);
                }
                it.set(resourceScope);
            }
        }
        Set<String> tags = new HashSet<String>();
        Tag[] tag = registry.getTags(artifactPath);
        for (Tag tag1 : tag) {
            tags.add(tag1.getTagName());
        }
        apiProduct.addTags(tags);
        for (APIProductResource resource : resources) {
            String apiPath = APIUtil.getAPIPath(resource.getApiIdentifier());
            Resource productResource = null;
            try {
                // Handles store and publisher visibility issue when associated apis have different visibility
                // restrictions.
                productResource = registry.get(apiPath);
            } catch (RegistryException e) {
                if (e.getClass().equals(AuthorizationFailedException.class)) {
                    if (log.isDebugEnabled()) {
                        log.debug("User is not authorized to access the resource " + apiPath);
                    }
                    continue;
                } else {
                    String msg = "Failed to get product resource";
                    throw new APIManagementException(msg, e);
                }
            }
            String artifactId = productResource.getUUID();
            resource.setApiId(artifactId);
            GenericArtifactManager artifactManager = getArtifactManager(registry, APIConstants.API_KEY);
            GenericArtifact apiArtifact = artifactManager.getGenericArtifact(resource.getApiId());
            API api = getAPI(apiArtifact, registry);
            resource.setEndpointConfig(api.getEndpointConfig());
            resource.setEndpointSecurityMap(setEndpointSecurityForAPIProduct(api));
        }
        apiProduct.setProductResources(resources);
        // set data and status related to monetization
        apiProduct.setMonetizationStatus(Boolean.parseBoolean(artifact.getAttribute(APIConstants.Monetization.API_MONETIZATION_STATUS)));
        String monetizationInfo = artifact.getAttribute(APIConstants.Monetization.API_MONETIZATION_PROPERTIES);
        if (StringUtils.isNotBlank(monetizationInfo)) {
            JSONParser parser = new JSONParser();
            JSONObject jsonObj = (JSONObject) parser.parse(monetizationInfo);
            apiProduct.setMonetizationProperties(jsonObj);
        }
        apiProduct.setApiCategories(getAPICategoriesFromAPIGovernanceArtifact(artifact, tenantId));
    } catch (GovernanceException e) {
        String msg = "Failed to get API Product for artifact ";
        throw new APIManagementException(msg, e);
    } catch (RegistryException e) {
        String msg = "Failed to get LastAccess time or Rating";
        throw new APIManagementException(msg, e);
    } catch (UserStoreException e) {
        String msg = "Failed to get User Realm of API Product Provider";
        throw new APIManagementException(msg, e);
    } catch (ParseException e) {
        String msg = "Failed to get parse monetization information.";
        throw new APIManagementException(msg, e);
    }
    return apiProduct;
}
Also used : LinkedHashMap(java.util.LinkedHashMap) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Tier(org.wso2.carbon.apimgt.api.model.Tier) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) ListIterator(java.util.ListIterator) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint) Scope(org.wso2.carbon.apimgt.api.model.Scope) AuthScope(org.apache.http.auth.AuthScope) JSONObject(org.json.simple.JSONObject) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) AuthorizationFailedException(org.wso2.carbon.registry.core.secure.AuthorizationFailedException) APIMgtAuthorizationFailedException(org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException) API(org.wso2.carbon.apimgt.api.model.API) JSONParser(org.json.simple.parser.JSONParser) Tag(org.wso2.carbon.registry.core.Tag) ParseException(org.json.simple.parser.ParseException)

Example 57 with Tag

use of org.wso2.carbon.registry.core.Tag in project carbon-apimgt by wso2.

the class APIUtil method getAPI.

/**
 * This method used to get API from governance artifact specific to copyAPI
 *
 * @param artifact API artifact
 * @param registry Registry
 * @return API
 * @throws APIManagementException if failed to get API from artifact
 */
public static API getAPI(GovernanceArtifact artifact, Registry registry, APIIdentifier oldId, String oldContext) throws APIManagementException {
    API api;
    try {
        String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
        String apiName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
        String apiVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
        api = new API(new APIIdentifier(providerName, apiName, apiVersion));
        int apiId = ApiMgtDAO.getInstance().getAPIID(artifact.getId());
        if (apiId == -1) {
            return null;
        }
        // set rating
        String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
        BigDecimal bigDecimal = BigDecimal.valueOf(registry.getAverageRating(artifactPath));
        BigDecimal res = bigDecimal.setScale(1, RoundingMode.HALF_UP);
        api.setRating(res.floatValue());
        // set description
        api.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
        // set last access time
        api.setLastUpdated(registry.get(artifactPath).getLastModified());
        // set uuid
        api.setUUID(artifact.getId());
        // set url
        api.setStatus(getLcStateFromArtifact(artifact));
        api.setThumbnailUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
        api.setWsdlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WSDL));
        api.setWadlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WADL));
        api.setTechnicalOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER));
        api.setTechnicalOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL));
        api.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER));
        api.setBusinessOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL));
        api.setEndpointSecured(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_SECURED)));
        api.setEndpointAuthDigest(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_AUTH_DIGEST)));
        api.setEndpointUTUsername(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_USERNAME));
        if (!((APIConstants.DEFAULT_MODIFIED_ENDPOINT_PASSWORD).equals(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD)))) {
            api.setEndpointUTPassword(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD));
        } else {
            // If APIEndpointPasswordRegistryHandler is enabled take password from the registry hidden property
            api.setEndpointUTPassword(getActualEpPswdFromHiddenProperty(api, registry));
        }
        api.setTransports(artifact.getAttribute(APIConstants.API_OVERVIEW_TRANSPORTS));
        api.setEndpointConfig(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG));
        api.setRedirectURL(artifact.getAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL));
        api.setApiOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_OWNER));
        api.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
        api.setSubscriptionAvailability(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY));
        api.setSubscriptionAvailableTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS));
        api.setResponseCache(artifact.getAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING));
        api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
        api.setVisibility(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY));
        String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(providerName));
        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomainName);
        String apiLevelTier = ApiMgtDAO.getInstance().getAPILevelTier(apiId);
        api.setApiLevelPolicy(apiLevelTier);
        String tiers = artifact.getAttribute(APIConstants.API_OVERVIEW_TIER);
        Map<String, Tier> definedTiers = getTiers(tenantId);
        Set<Tier> availableTier = getAvailableTiers(definedTiers, tiers, apiName);
        api.addAvailableTiers(availableTier);
        api.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT));
        api.setContextTemplate(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
        api.setLatest(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_LATEST)));
        ArrayList<URITemplate> urlPatternsList;
        Map<String, Scope> scopeToKeyMapping = getAPIScopes(artifact.getId(), tenantDomainName);
        api.setScopes(new LinkedHashSet<>(scopeToKeyMapping.values()));
        HashMap<Integer, Set<String>> resourceScopes;
        resourceScopes = ApiMgtDAO.getInstance().getResourceToScopeMapping(artifact.getId());
        urlPatternsList = ApiMgtDAO.getInstance().getAllURITemplates(oldContext, oldId.getVersion());
        Set<URITemplate> uriTemplates = new HashSet<URITemplate>(urlPatternsList);
        for (URITemplate uriTemplate : uriTemplates) {
            uriTemplate.setResourceURI(api.getUrl());
            uriTemplate.setResourceSandboxURI(api.getSandboxUrl());
            List<String> templateScopeKeys = new ArrayList<>(resourceScopes.get(uriTemplate.getId()));
            List<Scope> newTemplateScopes = new ArrayList<>();
            if (!templateScopeKeys.isEmpty()) {
                for (String templateScope : templateScopeKeys) {
                    Scope scope = scopeToKeyMapping.get(templateScope);
                    newTemplateScopes.add(scope);
                }
            }
            uriTemplate.addAllScopes(newTemplateScopes);
        }
        api.setUriTemplates(uriTemplates);
        Set<String> tags = new HashSet<String>();
        Tag[] tag = registry.getTags(artifactPath);
        for (Tag tag1 : tag) {
            tags.add(tag1.getTagName());
        }
        api.addTags(tags);
        api.setLastUpdated(registry.get(artifactPath).getLastModified());
        api.setAsDefaultVersion(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_DEFAULT_VERSION)));
        String environments = artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS);
        api.setEnvironments(extractEnvironmentsForAPI(environments));
        api.setCorsConfiguration(getCorsConfigurationFromArtifact(artifact));
    } catch (GovernanceException e) {
        String msg = "Failed to get API fro artifact ";
        throw new APIManagementException(msg, e);
    } catch (RegistryException e) {
        String msg = "Failed to get LastAccess time or Rating";
        throw new APIManagementException(msg, e);
    } catch (UserStoreException e) {
        String msg = "Failed to get User Realm of API Provider";
        throw new APIManagementException(msg, e);
    }
    return api;
}
Also used : SortedSet(java.util.SortedSet) HashSet(java.util.HashSet) Set(java.util.Set) TreeSet(java.util.TreeSet) LinkedHashSet(java.util.LinkedHashSet) ArrayList(java.util.ArrayList) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) Tier(org.wso2.carbon.apimgt.api.model.Tier) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint) BigDecimal(java.math.BigDecimal) BigInteger(java.math.BigInteger) Scope(org.wso2.carbon.apimgt.api.model.Scope) AuthScope(org.apache.http.auth.AuthScope) API(org.wso2.carbon.apimgt.api.model.API) Tag(org.wso2.carbon.registry.core.Tag)

Example 58 with Tag

use of org.wso2.carbon.registry.core.Tag in project jaggery by wso2.

the class RegistryHostObject method jsFunction_search.

public static Scriptable jsFunction_search(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws ScriptException {
    String functionName = "search";
    int argsCount = args.length;
    if (argsCount != 1) {
        HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
    }
    if (!(args[0] instanceof NativeObject)) {
        HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "json", args[0], false);
    }
    NativeObject options = (NativeObject) args[0];
    CustomSearchParameterBean parameters = new CustomSearchParameterBean();
    String path = null;
    List<String[]> values = new ArrayList<String[]>();
    DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
    String val;
    for (Object idObj : options.getIds()) {
        String id = (String) idObj;
        Object value = options.get(id, options);
        if (value == null || value instanceof Undefined) {
            continue;
        }
        if ("path".equals(id)) {
            path = (String) value;
            continue;
        }
        if ("createdBefore".equals(id) || "createdAfter".equals(id) || "updatedBefore".equals(id) || "updatedAfter".equals(id)) {
            long t;
            if (value instanceof Number) {
                t = ((Number) value).longValue();
            } else {
                t = Long.parseLong(HostObjectUtil.serializeObject(value));
            }
            val = new String(dateFormat.format(new Date(t)).getBytes());
        } else {
            val = HostObjectUtil.serializeObject(value);
        }
        values.add(new String[] { id, val });
    }
    parameters.setParameterValues(values.toArray(new String[0][0]));
    RegistryHostObject registryHostObject = (RegistryHostObject) thisObj;
    int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    try {
        UserRegistry userRegistry = RegistryHostObjectContext.getRegistryService().getRegistry(registryHostObject.registry.getUserName(), tenantId);
        Registry configRegistry = RegistryHostObjectContext.getRegistryService().getConfigSystemRegistry(tenantId);
        AdvancedSearchResultsBean resultsBean = registryHostObject.search(configRegistry, userRegistry, parameters);
        if (resultsBean.getResourceDataList() == null) {
            ScriptableObject error = (ScriptableObject) cx.newObject(thisObj);
            error.put("error", error, true);
            error.put("description", error, resultsBean.getErrorMessage());
            return error;
        }
        List<ScriptableObject> results = new ArrayList<ScriptableObject>();
        for (ResourceData resourceData : resultsBean.getResourceDataList()) {
            String resourcePath = resourceData.getResourcePath();
            if (path != null && !resourcePath.startsWith(path)) {
                continue;
            }
            ScriptableObject result = (ScriptableObject) cx.newObject(thisObj);
            result.put("author", result, resourceData.getAuthorUserName());
            result.put("rating", result, resourceData.getAverageRating());
            result.put("created", result, resourceData.getCreatedOn().getTime().getTime());
            result.put("description", result, resourceData.getDescription());
            result.put("name", result, resourceData.getName());
            result.put("path", result, resourceData.getResourcePath());
            List<ScriptableObject> tags = new ArrayList<ScriptableObject>();
            if (resourceData.getTagCounts() != null) {
                for (TagCount tagCount : resourceData.getTagCounts()) {
                    ScriptableObject tag = (ScriptableObject) cx.newObject(thisObj);
                    tag.put("name", tag, tagCount.getKey());
                    tag.put("count", tag, tagCount.getValue());
                    tags.add(tag);
                }
            }
            result.put("tags", result, cx.newArray(thisObj, tags.toArray()));
            results.add(result);
        }
        return cx.newArray(thisObj, results.toArray());
    } catch (RegistryException e) {
        throw new ScriptException(e);
    } catch (CarbonException e) {
        throw new ScriptException(e);
    }
}
Also used : CustomSearchParameterBean(org.wso2.carbon.registry.search.beans.CustomSearchParameterBean) ResourceData(org.wso2.carbon.registry.common.ResourceData) CarbonException(org.wso2.carbon.CarbonException) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) RegistryException(org.wso2.carbon.registry.api.RegistryException) AdvancedSearchResultsBean(org.wso2.carbon.registry.search.beans.AdvancedSearchResultsBean) ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException) TagCount(org.wso2.carbon.registry.common.TagCount) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) SimpleDateFormat(java.text.SimpleDateFormat)

Example 59 with Tag

use of org.wso2.carbon.registry.core.Tag in project ballerina by ballerina-lang.

the class TypeChecker method visit.

public void visit(BLangRecordLiteral recordLiteral) {
    BType actualType = symTable.errType;
    int expTypeTag = expTypes.get(0).tag;
    if (expTypeTag == TypeTags.NONE || expTypeTag == TypeTags.ANY) {
        // var a = {}
        // Change the expected type to map
        expTypes = Lists.of(symTable.mapType);
    }
    List<BType> matchedTypeList = getRecordCompatibleType(expTypes.get(0));
    if (matchedTypeList.isEmpty()) {
        dlog.error(recordLiteral.pos, DiagnosticCode.INVALID_LITERAL_FOR_TYPE, expTypes.get(0));
    } else if (matchedTypeList.size() > 1) {
        dlog.error(recordLiteral.pos, DiagnosticCode.AMBIGUOUS_TYPES, expTypes.get(0));
    } else {
        recordLiteral.keyValuePairs.forEach(keyValuePair -> checkRecLiteralKeyValue(keyValuePair, matchedTypeList.get(0)));
        actualType = matchedTypeList.get(0);
        // TODO Following check can be moved the code analyzer.
        if (expTypeTag == TypeTags.STRUCT) {
            validateStructInitalizer(recordLiteral.pos);
        }
    }
    resultTypes = types.checkTypes(recordLiteral, Lists.of(actualType), expTypes);
}
Also used : Arrays(java.util.Arrays) BTupleType(org.wso2.ballerinalang.compiler.semantics.model.types.BTupleType) BMapType(org.wso2.ballerinalang.compiler.semantics.model.types.BMapType) BLangIdentifier(org.wso2.ballerinalang.compiler.tree.BLangIdentifier) BLangXMLTextLiteral(org.wso2.ballerinalang.compiler.tree.expressions.BLangXMLTextLiteral) Map(java.util.Map) BLangVariableReference(org.wso2.ballerinalang.compiler.tree.expressions.BLangVariableReference) BEnumType(org.wso2.ballerinalang.compiler.semantics.model.types.BEnumType) BLangBinaryExpr(org.wso2.ballerinalang.compiler.tree.expressions.BLangBinaryExpr) Set(java.util.Set) SelectExpressionNode(org.ballerinalang.model.tree.clauses.SelectExpressionNode) BStructSymbol(org.wso2.ballerinalang.compiler.semantics.model.symbols.BStructSymbol) BLangLambdaFunction(org.wso2.ballerinalang.compiler.tree.expressions.BLangLambdaFunction) BLangSelectExpression(org.wso2.ballerinalang.compiler.tree.clauses.BLangSelectExpression) NamedArgNode(org.ballerinalang.model.tree.expressions.NamedArgNode) BLangXMLAttribute(org.wso2.ballerinalang.compiler.tree.expressions.BLangXMLAttribute) BLangNamedArgsExpression(org.wso2.ballerinalang.compiler.tree.expressions.BLangNamedArgsExpression) BLangTypeInit(org.wso2.ballerinalang.compiler.tree.expressions.BLangTypeInit) BLangRecordLiteral(org.wso2.ballerinalang.compiler.tree.expressions.BLangRecordLiteral) BLangIndexBasedAccess(org.wso2.ballerinalang.compiler.tree.expressions.BLangIndexBasedAccess) BLangXMLCommentLiteral(org.wso2.ballerinalang.compiler.tree.expressions.BLangXMLCommentLiteral) ArrayList(java.util.ArrayList) Flags(org.wso2.ballerinalang.util.Flags) BLangXMLQuotedString(org.wso2.ballerinalang.compiler.tree.expressions.BLangXMLQuotedString) TreeBuilder(org.ballerinalang.model.TreeBuilder) ExpressionNode(org.ballerinalang.model.tree.expressions.ExpressionNode) BType(org.wso2.ballerinalang.compiler.semantics.model.types.BType) BLangArrayLiteral(org.wso2.ballerinalang.compiler.tree.expressions.BLangArrayLiteral) BLangUnaryExpr(org.wso2.ballerinalang.compiler.tree.expressions.BLangUnaryExpr) DiagnosticPos(org.wso2.ballerinalang.compiler.util.diagnotic.DiagnosticPos) BArrayType(org.wso2.ballerinalang.compiler.semantics.model.types.BArrayType) SymbolEnv(org.wso2.ballerinalang.compiler.semantics.model.SymbolEnv) BLangXMLProcInsLiteral(org.wso2.ballerinalang.compiler.tree.expressions.BLangXMLProcInsLiteral) BLangForever(org.wso2.ballerinalang.compiler.tree.statements.BLangForever) BLangXMLQName(org.wso2.ballerinalang.compiler.tree.expressions.BLangXMLQName) BLangOrderBy(org.wso2.ballerinalang.compiler.tree.clauses.BLangOrderBy) BLangSelectClause(org.wso2.ballerinalang.compiler.tree.clauses.BLangSelectClause) SymTag(org.wso2.ballerinalang.compiler.semantics.model.symbols.SymTag) BLangLiteral(org.wso2.ballerinalang.compiler.tree.expressions.BLangLiteral) BLangTableQuery(org.wso2.ballerinalang.compiler.tree.clauses.BLangTableQuery) BEndpointVarSymbol(org.wso2.ballerinalang.compiler.semantics.model.symbols.BEndpointVarSymbol) BLangBracedOrTupleExpr(org.wso2.ballerinalang.compiler.tree.expressions.BLangBracedOrTupleExpr) CompilerContext(org.wso2.ballerinalang.compiler.util.CompilerContext) BInvokableType(org.wso2.ballerinalang.compiler.semantics.model.types.BInvokableType) BLangTypeConversionExpr(org.wso2.ballerinalang.compiler.tree.expressions.BLangTypeConversionExpr) BLangXMLAttributeAccess(org.wso2.ballerinalang.compiler.tree.expressions.BLangXMLAttributeAccess) Lists(org.wso2.ballerinalang.util.Lists) BVarSymbol(org.wso2.ballerinalang.compiler.semantics.model.symbols.BVarSymbol) OperatorKind(org.ballerinalang.model.tree.OperatorKind) BLangHaving(org.wso2.ballerinalang.compiler.tree.clauses.BLangHaving) BOperatorSymbol(org.wso2.ballerinalang.compiler.semantics.model.symbols.BOperatorSymbol) Names(org.wso2.ballerinalang.compiler.util.Names) BLangDiagnosticLog(org.wso2.ballerinalang.compiler.util.diagnotic.BLangDiagnosticLog) BLangSimpleVarRef(org.wso2.ballerinalang.compiler.tree.expressions.BLangSimpleVarRef) MultiReturnExpr(org.wso2.ballerinalang.compiler.tree.expressions.MultiReturnExpr) BXMLNSSymbol(org.wso2.ballerinalang.compiler.semantics.model.symbols.BXMLNSSymbol) BStructType(org.wso2.ballerinalang.compiler.semantics.model.types.BStructType) BLangExpression(org.wso2.ballerinalang.compiler.tree.expressions.BLangExpression) BLangRecordKey(org.wso2.ballerinalang.compiler.tree.expressions.BLangRecordLiteral.BLangRecordKey) BConversionOperatorSymbol(org.wso2.ballerinalang.compiler.semantics.model.symbols.BConversionOperatorSymbol) BSymbol(org.wso2.ballerinalang.compiler.semantics.model.symbols.BSymbol) BPackageSymbol(org.wso2.ballerinalang.compiler.semantics.model.symbols.BPackageSymbol) Collectors(java.util.stream.Collectors) BLangFieldBasedAccess(org.wso2.ballerinalang.compiler.tree.expressions.BLangFieldBasedAccess) List(java.util.List) NodeKind(org.ballerinalang.model.tree.NodeKind) BLangTableQueryExpression(org.wso2.ballerinalang.compiler.tree.expressions.BLangTableQueryExpression) BLangUserDefinedType(org.wso2.ballerinalang.compiler.tree.types.BLangUserDefinedType) BLangStreamingInput(org.wso2.ballerinalang.compiler.tree.clauses.BLangStreamingInput) BLangNodeVisitor(org.wso2.ballerinalang.compiler.tree.BLangNodeVisitor) BLangTypeofExpr(org.wso2.ballerinalang.compiler.tree.expressions.BLangTypeofExpr) TypeTags(org.wso2.ballerinalang.compiler.util.TypeTags) HashSet(java.util.HashSet) IterableKind(org.wso2.ballerinalang.compiler.semantics.model.iterable.IterableKind) BLangStringTemplateLiteral(org.wso2.ballerinalang.compiler.tree.expressions.BLangStringTemplateLiteral) BInvokableSymbol(org.wso2.ballerinalang.compiler.semantics.model.symbols.BInvokableSymbol) BLangTernaryExpr(org.wso2.ballerinalang.compiler.tree.expressions.BLangTernaryExpr) BFutureType(org.wso2.ballerinalang.compiler.semantics.model.types.BFutureType) BLangIntRangeExpression(org.wso2.ballerinalang.compiler.tree.expressions.BLangIntRangeExpression) BLangRecordKeyValue(org.wso2.ballerinalang.compiler.tree.expressions.BLangRecordLiteral.BLangRecordKeyValue) XMLConstants(javax.xml.XMLConstants) BUnionType(org.wso2.ballerinalang.compiler.semantics.model.types.BUnionType) BTransformerSymbol(org.wso2.ballerinalang.compiler.semantics.model.symbols.BTransformerSymbol) BJSONType(org.wso2.ballerinalang.compiler.semantics.model.types.BJSONType) RecordKind(org.wso2.ballerinalang.compiler.semantics.analyzer.Types.RecordKind) Symbols(org.wso2.ballerinalang.compiler.semantics.model.symbols.Symbols) BLangGroupBy(org.wso2.ballerinalang.compiler.tree.clauses.BLangGroupBy) Type(org.ballerinalang.model.types.Type) Name(org.wso2.ballerinalang.compiler.util.Name) BLangJoinStreamingInput(org.wso2.ballerinalang.compiler.tree.clauses.BLangJoinStreamingInput) BLangAwaitExpr(org.wso2.ballerinalang.compiler.tree.expressions.BLangAwaitExpr) BLangRestArgsExpression(org.wso2.ballerinalang.compiler.tree.expressions.BLangRestArgsExpression) BLangXMLElementLiteral(org.wso2.ballerinalang.compiler.tree.expressions.BLangXMLElementLiteral) FieldType(org.wso2.ballerinalang.compiler.util.FieldType) DiagnosticCode(org.ballerinalang.util.diagnostic.DiagnosticCode) BLangInvocation(org.wso2.ballerinalang.compiler.tree.expressions.BLangInvocation) Collections(java.util.Collections) SymbolTable(org.wso2.ballerinalang.compiler.semantics.model.SymbolTable) BType(org.wso2.ballerinalang.compiler.semantics.model.types.BType)

Example 60 with Tag

use of org.wso2.carbon.registry.core.Tag in project ballerina by ballerina-lang.

the class TypeChecker method visit.

@Override
public void visit(BLangTableQueryExpression tableQueryExpression) {
    BType actualType = symTable.errType;
    int expTypeTag = expTypes.get(0).tag;
    if (expTypeTag == TypeTags.TABLE) {
        actualType = expTypes.get(0);
    } else if (expTypeTag != TypeTags.ERROR) {
        dlog.error(tableQueryExpression.pos, DiagnosticCode.INCOMPATIBLE_TYPES_CONVERSION, expTypes.get(0));
    }
    BLangTableQuery tableQuery = (BLangTableQuery) tableQueryExpression.getTableQuery();
    tableQuery.accept(this);
    resultTypes = types.checkTypes(tableQueryExpression, Lists.of(actualType), expTypes);
}
Also used : BLangTableQuery(org.wso2.ballerinalang.compiler.tree.clauses.BLangTableQuery) BType(org.wso2.ballerinalang.compiler.semantics.model.types.BType)

Aggregations

ArrayList (java.util.ArrayList)21 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)21 Registry (org.wso2.carbon.registry.core.Registry)20 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)19 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)18 Tag (org.wso2.carbon.registry.core.Tag)18 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)18 API (org.wso2.carbon.apimgt.api.model.API)17 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)16 Resource (org.wso2.carbon.registry.core.Resource)16 DevPortalAPI (org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI)14 UserStoreException (org.wso2.carbon.user.api.UserStoreException)14 HashSet (java.util.HashSet)13 BType (org.wso2.ballerinalang.compiler.semantics.model.types.BType)12 Test (org.junit.Test)11 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)11 JSONObject (org.json.simple.JSONObject)10 Tag (org.wso2.carbon.apimgt.api.model.Tag)10 List (java.util.List)9 GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)9