Search in sources :

Example 81 with ResourcePath

use of org.wso2.carbon.apimgt.api.model.ResourcePath in project carbon-apimgt by wso2.

the class PoliciesApiServiceImpl method policiesMediationMediationPolicyIdPut.

/**
 * Updates an existing global mediation policy
 *
 * @param mediationPolicyId uuid of mediation policy
 * @param body              updated MediationDTO
 * @param contentType       Content-Type header
 * @return updated mediation DTO as response
 */
@Override
public Response policiesMediationMediationPolicyIdPut(String mediationPolicyId, String contentType, MediationDTO body, MessageContext messageContext) {
    InputStream contentStream = null;
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        // Get registry resource correspond to given uuid
        Resource mediationResource = apiProvider.getCustomMediationResourceFromUuid(mediationPolicyId);
        if (mediationResource != null) {
            // extracting already existing name of the mediation policy
            String contentString = IOUtils.toString(mediationResource.getContentStream(), RegistryConstants.DEFAULT_CHARSET_ENCODING);
            // Get policy name from the mediation config
            OMElement omElement = AXIOMUtil.stringToOM(contentString);
            OMAttribute attribute = omElement.getAttribute(new QName(PolicyConstants.MEDIATION_NAME_ATTRIBUTE));
            String existingMediationPolicyName = attribute.getAttributeValue();
            // replacing the name of the body with existing name
            body.setName(existingMediationPolicyName);
            // Getting mediation config to be update from the body
            contentStream = new ByteArrayInputStream(body.getConfig().getBytes(StandardCharsets.UTF_8));
            // Creating new resource file
            ResourceFile contentFile = new ResourceFile(contentStream, contentType);
            // Getting registry path of the existing resource
            String resourcePath = mediationResource.getPath();
            // Updating the existing global mediation policy
            // No need to check API permission, hence null as api identifier
            String updatedPolicyUrl = apiProvider.addResourceFile(null, resourcePath, contentFile);
            if (StringUtils.isNotBlank(updatedPolicyUrl)) {
                // Getting uuid of updated global mediation policy
                String uuid = apiProvider.getCreatedResourceUuid(resourcePath);
                // Getting updated mediation
                Mediation updatedMediation = apiProvider.getGlobalMediationPolicy(uuid);
                MediationDTO updatedMediationDTO = MediationMappingUtil.fromMediationToDTO(updatedMediation);
                URI uploadedMediationUri = new URI(updatedPolicyUrl);
                return Response.ok(uploadedMediationUri).entity(updatedMediationDTO).build();
            }
        } else {
            // If resource not exists
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_POLICY, mediationPolicyId, log);
        }
    } catch (APIManagementException e) {
        String errorMessage = "Error while updating the global mediation policy " + body.getName();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (URISyntaxException e) {
        String errorMessage = "Error while getting location header for uploaded " + "mediation policy " + body.getName();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (XMLStreamException e) {
        String errorMessage = "Error occurred while converting the existing content stream of " + " mediation " + "policy to string";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (RegistryException e) {
        String errorMessage = "Error occurred while getting the existing content stream ";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (IOException e) {
        String errorMessage = "Error occurred while converting content stream in to string ";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } finally {
        IOUtils.closeQuietly(contentStream);
    }
    return null;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) QName(javax.xml.namespace.QName) Resource(org.wso2.carbon.registry.api.Resource) OMElement(org.apache.axiom.om.OMElement) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) MediationDTO(org.wso2.carbon.apimgt.rest.api.admin.v1.dto.MediationDTO) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) Mediation(org.wso2.carbon.apimgt.api.model.Mediation) URI(java.net.URI) RegistryException(org.wso2.carbon.registry.api.RegistryException) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) XMLStreamException(javax.xml.stream.XMLStreamException) ByteArrayInputStream(java.io.ByteArrayInputStream) OMAttribute(org.apache.axiom.om.OMAttribute)

Example 82 with ResourcePath

use of org.wso2.carbon.apimgt.api.model.ResourcePath 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 83 with ResourcePath

use of org.wso2.carbon.apimgt.api.model.ResourcePath in project jaggery by wso2.

the class RegistryHostObject method isAuthorized.

private boolean isAuthorized(UserRegistry registry, String resourcePath, String action) throws RegistryException {
    UserRealm userRealm = registry.getUserRealm();
    String userName = registry.getUserName();
    try {
        if (!userRealm.getAuthorizationManager().isUserAuthorized(userName, resourcePath, action)) {
            return false;
        }
    } catch (UserStoreException e) {
        throw new org.wso2.carbon.registry.core.exceptions.RegistryException("Error at Authorizing " + resourcePath + " with user " + userName + ":" + e.getMessage(), e);
    }
    return true;
}
Also used : UserRealm(org.wso2.carbon.user.core.UserRealm) UserStoreException(org.wso2.carbon.user.core.UserStoreException)

Aggregations

Resource (org.wso2.carbon.registry.core.Resource)51 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)48 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)44 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)28 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)25 IOException (java.io.IOException)18 Registry (org.wso2.carbon.registry.core.Registry)16 Collection (org.wso2.carbon.registry.core.Collection)15 UserStoreException (org.wso2.carbon.user.api.UserStoreException)14 Test (org.junit.Test)13 Resource (org.wso2.carbon.registry.api.Resource)13 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)12 ArrayList (java.util.ArrayList)11 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)11 RegistryException (org.wso2.carbon.registry.api.RegistryException)11 ResourceImpl (org.wso2.carbon.registry.core.ResourceImpl)11 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)11 JSONParser (org.json.simple.parser.JSONParser)10 ParseException (org.json.simple.parser.ParseException)10 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)10