/** * This method retrieves the resource paths for a given tag name * * @param tagName - Name of the tag * @param start - Page start number * @param size - Number of records to be fetched * @return JSON object eg: {"path":[<array of resource paths tagged by the tagname>]}protected * HTTP 200 OK. */ @GET @Produces("application/json") public Response getTaggedResources( @QueryParam("name") String tagName, @QueryParam("start") int start, @QueryParam("size") int size, @HeaderParam("X-JWT-Assertion") String JWTToken) { RestAPIAuthContext authContext = RestAPISecurityUtils.getAuthContext( PrivilegedCarbonContext.getThreadLocalCarbonContext(), JWTToken); if (!authContext.isAuthorized()) { return Response.status(Response.Status.UNAUTHORIZED).build(); } try { Registry registry = getUserRegistry(authContext.getUserName(), authContext.getTenantId()); TaggedResourcePath[] resourcePaths = registry.getResourcePathsWithTag(tagName); return getPaginatedResults(resourcePaths, start, size, "", ""); } catch (RegistryException e) { log.error("Failed to get resource path having tag : " + tagName, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } }
/** * Creates a collection in the given common location. * * @param commonLocation location to create the collection. * @throws RegistryException If fails to create a collection at given location. */ private void createCollection(String commonLocation) throws RegistryException { Registry systemRegistry = CommonUtil.getUnchrootedSystemRegistry(requestContext); // Creating a collection if not exists. if (!systemRegistry.resourceExists(commonLocation)) { systemRegistry.put(commonLocation, systemRegistry.newCollection()); } }
public static boolean addHandler(Registry configSystemRegistry, String payload) throws RegistryException, XMLStreamException { String name; OMElement element = AXIOMUtil.stringToOM(payload); if (element != null) { name = element.getAttributeValue(new QName("class")); } else return false; if (isHandlerNameInUse(name)) throw new RegistryException("The added handler name is already in use!"); String path = getContextRoot() + name; Resource resource; if (!handlerExists(configSystemRegistry, name)) { resource = new ResourceImpl(); } else { throw new RegistryException("The added handler name is already in use!"); } resource.setContent(payload); try { configSystemRegistry.beginTransaction(); configSystemRegistry.put(path, resource); generateHandler(configSystemRegistry, path); configSystemRegistry.commitTransaction(); } catch (Exception e) { configSystemRegistry.rollbackTransaction(); throw new RegistryException("Unable to generate handler", e); } return true; }
public static void cleanupResources(Registry registry) throws RegistryException { for (String string : new String[] { "/trunk/services", "/trunk/wsdls", "/trunk", "/branches", "/departments", "/organizations", "/project-groups", "/people", "/applications", "/processes", "/projects", "/test_suites", "/test_cases", "/test_harnesses", "/test_methods" }) { if (registry.resourceExists(string)) { try { registry.delete(string); } catch (Exception skip) { } } } }
public static String[] getHandlerList(Registry configSystemRegistry) throws RegistryException { Collection collection; try { collection = (Collection) configSystemRegistry.get(getContextRoot()); } catch (Exception e) { return null; } if (collection == null) { CollectionImpl handlerCollection = new CollectionImpl(); configSystemRegistry.put(getContextRoot(), handlerCollection); return null; } else { if (collection.getChildCount() == 0) { return null; } String[] childrenList = collection.getChildren(); String[] handlerNameList = new String[collection.getChildCount()]; for (int i = 0; i < childrenList.length; i++) { String path = childrenList[i]; handlerNameList[i] = path.substring(path.lastIndexOf(RegistryConstants.PATH_SEPARATOR) + 1); } return handlerNameList; } }
public static boolean addDefaultHandlersIfNotAvailable(Registry configSystemRegistry) throws RegistryException, FileNotFoundException, XMLStreamException { if (!configSystemRegistry.resourceExists(RegistryConstants.HANDLER_CONFIGURATION_PATH)) { Collection handlerConfigurationCollection = new CollectionImpl(); String description = "Handler configurations are stored here."; handlerConfigurationCollection.setDescription(description); configSystemRegistry.put( RegistryConstants.HANDLER_CONFIGURATION_PATH, handlerConfigurationCollection); // We don't have any default handler configuration as in lifecycles. } else { // configue all handlers Resource handlerRoot = configSystemRegistry.get(getContextRoot()); if (!(handlerRoot instanceof Collection)) { String msg = "Failed to continue as the handler configuration root: " + getContextRoot() + " is not a collection."; log.error(msg); throw new RegistryException(msg); } Collection handlerRootCol = (Collection) handlerRoot; String[] handlerConfigPaths = handlerRootCol.getChildren(); if (handlerConfigPaths != null) { for (String handlerConfigPath : handlerConfigPaths) { generateHandler(configSystemRegistry, handlerConfigPath); } } } return true; }
/** * Remove trusted service * * @param groupName Group name * @param serviceName Service name * @param trustedService Trusted service name * @throws org.wso2.carbon.security.SecurityConfigException */ private void removeTrustedService(String groupName, String serviceName, String trustedService) throws SecurityConfigException { Registry registry; String resourcePath; Resource resource; try { resourcePath = RegistryResources.SERVICE_GROUPS + groupName + RegistryResources.SERVICES + serviceName + "/trustedServices"; registry = getConfigSystemRegistry(); if (registry != null) { if (registry.resourceExists(resourcePath)) { resource = registry.get(resourcePath); if (resource.getProperty(trustedService) != null) { resource.removeProperty(trustedService); } registry.put(resourcePath, resource); } } } catch (Exception e) { String error = "Error occurred while removing trusted service for STS"; log.error(error, e); throw new SecurityConfigException(error, e); } }
/** * This method add array of tags to the specified resource * * @param resourcePath - Resource path * @return HTTP 204 No Content if success */ @POST @Consumes("application/json") @Produces("application/json") public Response addTag( @QueryParam("path") String resourcePath, @QueryParam("name") String tagText, @HeaderParam("X-JWT-Assertion") String JWTToken) { RestAPIAuthContext authContext = RestAPISecurityUtils.getAuthContext( PrivilegedCarbonContext.getThreadLocalCarbonContext(), JWTToken); if (!authContext.isAuthorized()) { return Response.status(Response.Status.UNAUTHORIZED).build(); } try { Registry registry = getUserRegistry(authContext.getUserName(), authContext.getTenantId()); if (!registry.resourceExists(resourcePath)) { return Response.status(Response.Status.NOT_FOUND) .entity(RestAPIConstants.RESOURCE_NOT_FOUND + resourcePath) .build(); } registry.applyTag(resourcePath, tagText); return Response.status(Response.Status.NO_CONTENT).build(); } catch (RegistryException e) { log.error("user doesn't have permission to put the tags for the given resource", e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } }
public RegistryManager() { try { if (!registry.resourceExists(CartridgeConstants.DomainMappingInfo.HOSTINFO)) { registry.put(CartridgeConstants.DomainMappingInfo.HOSTINFO, registry.newCollection()); } } catch (RegistryException e) { String msg = "Error while accessing registry or initializing domain mapping registry path\n"; log.error(msg + e.getMessage()); } }
/** * Creates and returns an InputStream from the file path / http location given. * * @throws DataServiceFault * @see InputStream */ public static InputStream getInputStreamFromPath(String path) throws IOException, DataServiceFault { InputStream ins; if (path.startsWith("http://")) { /* This is a url file path */ URL url = new URL(path); ins = url.openStream(); } else if (isRegistryPath(path)) { try { RegistryService registryService = DataServicesDSComponent.getRegistryService(); if (registryService == null) { throw new DataServiceFault( "DBUtils.getInputStreamFromPath(): Registry service is not available"); } Registry registry; if (path.startsWith(DBConstants.CONF_REGISTRY_PATH_PREFIX)) { if (path.length() > DBConstants.CONF_REGISTRY_PATH_PREFIX.length()) { path = path.substring(DBConstants.CONF_REGISTRY_PATH_PREFIX.length()); registry = registryService.getConfigSystemRegistry(getCurrentTenantId()); } else { throw new DataServiceFault("Empty configuration registry path given"); } } else { if (path.length() > DBConstants.GOV_REGISTRY_PATH_PREFIX.length()) { path = path.substring(DBConstants.GOV_REGISTRY_PATH_PREFIX.length()); registry = registryService.getGovernanceSystemRegistry(getCurrentTenantId()); } else { throw new DataServiceFault("Empty governance registry path given"); } } if (registry.resourceExists(path)) { Resource serviceResource = registry.get(path); ins = serviceResource.getContentStream(); } else { throw new DataServiceFault( "The given XSLT resource path at '" + path + "' does not exist"); } } catch (RegistryException e) { String msg = "Error in retrieving the resource: " + path; log.error(msg, e); throw new DataServiceFault(e, msg); } } else { File csvFile = new File(path); if (path.startsWith("." + File.separator) || path.startsWith(".." + File.separator)) { /* this is a relative path */ path = csvFile.getAbsolutePath(); } /* local file */ ins = new FileInputStream(path); } return ins; }
/** * @param policyStoreDTO * @return */ public static void addPolicyToPDP(PolicyStoreDTO policyStoreDTO) throws EntitlementException { Registry registry; String policyPath; Collection policyCollection; Resource resource; Map.Entry<PolicyStoreManageModule, Properties> entry = EntitlementServiceComponent.getEntitlementConfig() .getPolicyStore() .entrySet() .iterator() .next(); String policyStorePath = entry.getValue().getProperty("policyStorePath"); if (policyStorePath == null) { policyStorePath = "/repository/identity/Entitlement/actualStore/"; } if (policyStoreDTO == null || policyStoreDTO.getPolicy() == null || policyStoreDTO.getPolicy().trim().length() == 0 || policyStoreDTO.getPolicyId() == null || policyStoreDTO.getPolicyId().trim().length() == 0) { return; } try { registry = EntitlementServiceComponent.getRegistryService().getGovernanceSystemRegistry(); if (registry.resourceExists(policyStorePath)) { policyCollection = (Collection) registry.get(policyStorePath); } else { policyCollection = registry.newCollection(); } registry.put(policyStorePath, policyCollection); policyPath = policyStorePath + policyStoreDTO.getPolicyId(); if (registry.resourceExists(policyPath)) { resource = registry.get(policyPath); } else { resource = registry.newResource(); } resource.setProperty("policyOrder", Integer.toString(policyStoreDTO.getPolicyOrder())); resource.setContent(policyStoreDTO.getPolicy()); resource.setMediaType("application/xacml-policy+xml"); AttributeDTO[] attributeDTOs = policyStoreDTO.getAttributeDTOs(); if (attributeDTOs != null) { setAttributesAsProperties(attributeDTOs, resource); } registry.put(policyPath, resource); } catch (RegistryException e) { log.error(e); throw new EntitlementException("Error while adding policy to PDP", e); } }
/** * Adds swagger 1.2 api resource documents to registry and returns a list of resource documents as * JSON objects. * * @param swaggerDocObject swagger document JSON object. * @param sourceUrl source url of the swagger document. * @param swaggerDocPath swagger document path. (path of the registry) * @return List of api resources. * @throws RegistryException If fails to import or save resource docs to the registry. */ private List<JsonObject> addResourceDocsToRegistry( JsonObject swaggerDocObject, String sourceUrl, String swaggerDocPath) throws RegistryException { if (sourceUrl == null) { log.debug(CommonConstants.EMPTY_URL); log.warn("Resource paths cannot be read. Creating the REST service might fail."); return null; } else if (sourceUrl.startsWith("file")) { sourceUrl = sourceUrl.substring(0, sourceUrl.lastIndexOf("/")); } List<JsonObject> resourceObjects = new ArrayList<>(); // Adding Resource documents to registry. JsonArray pathResources = swaggerDocObject.get(SwaggerConstants.APIS).getAsJsonArray(); ByteArrayOutputStream resourceContentStream = null; InputStream resourceInputStream = null; String path; /* Loops through apis array of the swagger 1.2 api-doc and reads all the resource documents and saves them in to the registry. */ for (JsonElement pathResource : pathResources) { JsonObject resourceObj = pathResource.getAsJsonObject(); path = resourceObj.get(SwaggerConstants.PATH).getAsString(); try { resourceInputStream = new URL(sourceUrl + path).openStream(); } catch (IOException e) { throw new RegistryException("The URL " + sourceUrl + path + " is incorrect.", e); } resourceContentStream = CommonUtil.readSourceContent(resourceInputStream); JsonObject resourceObject = parser.parse(resourceContentStream.toString()).getAsJsonObject(); resourceObjects.add(resourceObject); if (endpointElement == null) { createEndpointElement(resourceObject, SwaggerConstants.SWAGGER_VERSION_12); } // path = swaggerResourcesPath + path; path = path.replace("/", ""); path = CommonUtil.replaceExpressionOfPath(swaggerResourcesPath, "name", path); path = RegistryUtils.getAbsolutePath(registry.getRegistryContext(), path); // Save Resource document to registry if (addSwaggerDocumentToRegistry(resourceContentStream, path, documentVersion)) { // Adding an dependency to API_DOC registry.addAssociation(swaggerDocPath, path, CommonConstants.DEPENDS); } } CommonUtil.closeOutputStream(resourceContentStream); CommonUtil.closeInputStream(resourceInputStream); return resourceObjects; }
public static Resource getRegistryResource(String path) throws DynamicClientRegistrationException { try { Registry governanceRegistry = DynamicClientWebAppRegistrationUtil.getGovernanceRegistry(); if (governanceRegistry.resourceExists(path)) { return governanceRegistry.get(path); } return null; } catch (RegistryException e) { throw new DynamicClientRegistrationException( "Error in retrieving registry resource : " + e.getMessage(), e); } }
public void testBackwardCompatibility() throws RegistryException { Registry rootRegistry = embeddedRegistryService.getSystemRegistry(); Resource r1 = rootRegistry.newResource(); r1.setContent("r1 content"); rootRegistry.put("/test/comments/r1", r1); rootRegistry.addComment( "/test/comments/r1", new Comment("backward-compatibility1 on this resource :)")); rootRegistry.addComment( "/test/comments/r1", new Comment("backward-compatibility2 on this resource :)")); String sql = "SELECT REG_COMMENT_ID FROM REG_COMMENT C, REG_RESOURCE_COMMENT RC " + "WHERE C.REG_COMMENT_TEXT LIKE ? AND C.REG_ID=RC.REG_COMMENT_ID"; Resource queryR = rootRegistry.newResource(); queryR.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE); queryR.addProperty( RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.COMMENTS_RESULT_TYPE); rootRegistry.put("/beep/x", queryR); Map<String, String> params = new HashMap<String, String>(); params.put("query", sql); params.put(RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.COMMENTS_RESULT_TYPE); params.put("1", "backward-compatibility1%"); Collection qResults = rootRegistry.executeQuery("/beep/x", params); String[] qPaths = (String[]) qResults.getContent(); assertEquals("Query result count should be 1", qPaths.length, 1); }
private void addService(String nameSpace, String serviceName) throws RegistryException { ServiceManager serviceManager = new ServiceManager(governance); Service service; service = serviceManager.newService(new QName(nameSpace, serviceName)); serviceManager.addService(service); for (String serviceId : serviceManager.getAllServiceIds()) { service = serviceManager.getService(serviceId); if (service.getPath().endsWith(serviceName)) { Resource resource = governance.get(service.getPath()); resource.addProperty("x", "10"); governance.put(service.getPath(), resource); } } }
/** * This method tags associated with the given resource * * @param resourcePath resource path * @param start starting page number * @param size number of tags to be fetched * @return JSON tag model eg: {"tags":[<array of tag names]} */ @GET @Produces("application/json") @ApiOperation( value = "Get all tags on a resource", httpMethod = "GET", notes = "Fetch all tags on a resource", response = TagModel.class) @ApiResponses( value = { @ApiResponse(code = 200, message = "Found the tags and returned in body"), @ApiResponse(code = 401, message = "Invalid credentials provided"), @ApiResponse(code = 404, message = "Given specific resource not found"), @ApiResponse(code = 500, message = "Internal server error occurred") }) public Response getTags( @QueryParam("path") String resourcePath, @QueryParam("start") int start, @QueryParam("size") int size, @HeaderParam("X-JWT-Assertion") String JWTToken) { RestAPIAuthContext authContext = RestAPISecurityUtils.getAuthContext( PrivilegedCarbonContext.getThreadLocalCarbonContext(), JWTToken); if (!authContext.isAuthorized()) { return Response.status(Response.Status.UNAUTHORIZED).build(); } if (resourcePath == null || "".equals(resourcePath)) { // Return tagsCloud, therefore no need pagination. return getAllTags(); } org.wso2.carbon.registry.core.Tag[] tags = new org.wso2.carbon.registry.core.Tag[0]; try { Registry registry = getUserRegistry(authContext.getUserName(), authContext.getTenantId()); if (!registry.resourceExists(resourcePath)) { return Response.status(Response.Status.NOT_FOUND) .entity(RestAPIConstants.RESOURCE_NOT_FOUND) .build(); } tags = registry.getTags(resourcePath); } catch (RegistryException e) { log.error("Failed to get tags on resource " + resourcePath, e); Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } // Need paginate, because it return tags of a resource return getPaginatedResults(tags, start, size, "", ""); }
public static boolean putRegistryResource(String path, Resource resource) throws DynamicClientRegistrationException { boolean status; try { Registry governanceRegistry = DynamicClientWebAppRegistrationUtil.getGovernanceRegistry(); governanceRegistry.beginTransaction(); governanceRegistry.put(path, resource); governanceRegistry.commitTransaction(); status = true; } catch (RegistryException e) { throw new DynamicClientRegistrationException( "Error occurred while persisting registry resource : " + e.getMessage(), e); } return status; }
public static boolean removeHandler(Registry configSystemRegistry, String handlerName) throws RegistryException, XMLStreamException { String handlerConfiguration = getHandlerConfiguration(configSystemRegistry, handlerName); if (handlerConfiguration != null) { OMElement element = AXIOMUtil.stringToOM(handlerConfiguration); try { try { configSystemRegistry.beginTransaction(); RegistryConfigurationProcessor.HandlerDefinitionObject handlerDefinitionObject = new RegistryConfigurationProcessor.HandlerDefinitionObject(null, element).invoke(); String[] methods = handlerDefinitionObject.getMethods(); Filter filter = handlerDefinitionObject.getFilter(); Handler handler = handlerDefinitionObject.getHandler(); if (handlerDefinitionObject.getTenantId() != -1) { CurrentSession.setCallerTenantId(handlerDefinitionObject.getTenantId()); // We need to swap the tenant id for this call, if the handler has overriden the // default value. configSystemRegistry .getRegistryContext() .getHandlerManager() .removeHandler( methods, filter, handler, HandlerLifecycleManager.USER_DEFINED_HANDLER_PHASE); CurrentSession.removeCallerTenantId(); } else { configSystemRegistry .getRegistryContext() .getHandlerManager() .removeHandler( methods, filter, handler, HandlerLifecycleManager.USER_DEFINED_HANDLER_PHASE); } configSystemRegistry.commitTransaction(); return true; } catch (Exception e) { configSystemRegistry.rollbackTransaction(); throw e; } } catch (Exception e) { if (e instanceof RegistryException) { throw (RegistryException) e; } else if (e instanceof XMLStreamException) { throw (XMLStreamException) e; } throw new RegistryException("Unable to build handler configuration", e); } } return false; }
/** * Configures the swagger resource path form its content and returns the swagger document path. * * @param rootLocation root location of the swagger files. * @param content swagger content. * @return Common resource path. */ private String getSwaggerDocumentPath(String rootLocation, JsonObject content) throws RegistryException { String swaggerDocPath = requestContext.getResourcePath().getPath(); String swaggerDocName = swaggerDocPath.substring(swaggerDocPath.lastIndexOf(RegistryConstants.PATH_SEPARATOR) + 1); JsonElement infoElement = content.get(SwaggerConstants.INFO); JsonObject infoObject = (infoElement != null) ? infoElement.getAsJsonObject() : null; if (infoObject == null || infoElement.isJsonNull()) { throw new RegistryException("Invalid swagger document."); } String serviceName = infoObject.get(SwaggerConstants.TITLE).getAsString().replaceAll("\\s", ""); String serviceProvider = CarbonContext.getThreadLocalCarbonContext().getUsername(); swaggerResourcesPath = rootLocation + serviceProvider + RegistryConstants.PATH_SEPARATOR + serviceName + RegistryConstants.PATH_SEPARATOR + documentVersion; String pathExpression = getSwaggerRegistryPath(swaggerDocName, serviceProvider); return RegistryUtils.getAbsolutePath(registry.getRegistryContext(), pathExpression); }
private void addPolicy() throws RegistryException, IOException { PolicyManager policyManager = new PolicyManager(governance); String policyFilePath = ProductConstant.getResourceLocations(ProductConstant.GREG_SERVER_NAME) + File.separator + "policy" + File.separator; Policy policy = policyManager.newPolicy( FileManager.readFile(policyFilePath + "UTPolicy.xml").getBytes(), "UTPolicy.xml"); policyManager.addPolicy(policy); policy = policyManager.getPolicy(policy.getId()); Resource resource = governance.get(policy.getPath()); resource.addProperty("abcxyzpqr", "40"); governance.put(policy.getPath(), resource); }
private OMElement resolveImports( OMElement grammarsElement, String wadlBaseUri, String wadlVersion) throws RegistryException { String wadlNamespace = grammarsElement.getNamespace().getNamespaceURI(); Iterator<OMElement> grammarElements = grammarsElement.getChildrenWithName(new QName(wadlNamespace, "include")); while (grammarElements.hasNext()) { OMElement childElement = grammarElements.next(); OMAttribute refAttr = childElement.getAttribute(new QName("href")); String importUrl = refAttr.getAttributeValue(); if (importUrl.endsWith(".xsd")) { if (!importUrl.startsWith("http")) { if (registry.resourceExists(importUrl)) { continue; } else { if (wadlBaseUri != null) { importUrl = wadlBaseUri + importUrl; } } } String schemaPath = saveSchema(importUrl, wadlVersion); importedSchemas.add(schemaPath); refAttr.setAttributeValue(schemaPath); childElement.addAttribute(refAttr); } } return grammarsElement; }
private void addSchema() throws IOException, RegistryException { SchemaManager schemaManager = new SchemaManager(governance); String schemaFilePath = ProductConstant.getResourceLocations(ProductConstant.GREG_SERVER_NAME) + File.separator + "schema" + File.separator; Schema schema = schemaManager.newSchema( FileManager.readFile(schemaFilePath + "Person.xsd").getBytes(), "Person.xsd"); schemaManager.addSchema(schema); schema = schemaManager.getSchema(schema.getId()); Resource resource = governance.get(schema.getPath()); resource.addProperty("z", "30"); governance.put(schema.getPath(), resource); }
/** * Method to obtain a list of paths having resources of the given media type. * * @param registry the registry instance to run query on. * @param mediaType the media type. * @return an array of resource paths. * @throws RegistryException if the operation failed. */ public static String[] getResultPaths(Registry registry, String mediaType) throws RegistryException { String[] result; String[] paginatedResult; try { Map<String, String> parameter = new HashMap<String, String>(); parameter.put("1", mediaType); parameter.put( "query", "SELECT DISTINCT REG_PATH_ID, REG_NAME FROM REG_RESOURCE WHERE REG_MEDIA_TYPE=?"); result = (String[]) registry.executeQuery(null, parameter).getContent(); if (result == null || result.length == 0) { return new String[0]; } result = removeMountPaths(result, registry); MessageContext messageContext = MessageContext.getCurrentMessageContext(); if (PaginationUtils.isPaginationAnnotationFound("getPaginatedGovernanceArtifacts") && ((messageContext != null && PaginationUtils.isPaginationHeadersExist(messageContext)) || PaginationContext.getInstance() != null)) { int rowCount = result.length; PaginationContext paginationContext; try { if (messageContext != null) { PaginationUtils.setRowCount(messageContext, Integer.toString(rowCount)); paginationContext = PaginationUtils.initPaginationContext(messageContext); } else { paginationContext = PaginationContext.getInstance(); } int start = paginationContext.getStart(); int count = paginationContext.getCount(); int startIndex; if (start == 1) { startIndex = 0; } else { startIndex = start; } if (rowCount < start + count) { paginatedResult = new String[rowCount - startIndex]; System.arraycopy(result, startIndex, paginatedResult, 0, (rowCount - startIndex)); } else { paginatedResult = new String[count]; System.arraycopy(result, startIndex, paginatedResult, 0, count); } return paginatedResult; } finally { PaginationContext.destroy(); } } } catch (RegistryException e) { String msg = "Error in getting the result for media type: " + mediaType + "."; log.error(msg, e); throw new RegistryException(msg, e); } return result; }
private void addWSDL() throws IOException, RegistryException { WsdlManager wsdlManager = new WsdlManager(governance); Wsdl wsdl; String wsdlFilePath = ProductConstant.getResourceLocations(ProductConstant.GREG_SERVER_NAME) + File.separator + "wsdl" + File.separator; wsdl = wsdlManager.newWsdl( FileManager.readFile(wsdlFilePath + "echo.wsdl").getBytes(), "echo.wsdl"); wsdlManager.addWsdl(wsdl); wsdl = wsdlManager.getWsdl(wsdl.getId()); Resource resource = governance.get(wsdl.getPath()); resource.addProperty("y", "20"); governance.put(wsdl.getPath(), resource); }
/** * This method deletes the specified tag on the given resource * * @param resourcePath - Path of the resource. * @param tagName - Name of the tag * @return HTTP 204 No Content response, if success. */ @DELETE @Produces("application/json") public Response deleteTag( @QueryParam("path") String resourcePath, @QueryParam("name") String tagName, @HeaderParam("X-JWT-Assertion") String JWTToken) { RestAPIAuthContext authContext = RestAPISecurityUtils.getAuthContext( PrivilegedCarbonContext.getThreadLocalCarbonContext(), JWTToken); if (!authContext.isAuthorized()) { return Response.status(Response.Status.UNAUTHORIZED).build(); } try { boolean tagFound = false; Registry registry = getUserRegistry(authContext.getUserName(), authContext.getTenantId()); if (!registry.resourceExists(resourcePath)) { return Response.status(Response.Status.NOT_FOUND) .entity(RestAPIConstants.RESOURCE_NOT_FOUND + resourcePath) .build(); } org.wso2.carbon.registry.core.Tag[] tags = registry.getTags(resourcePath); for (org.wso2.carbon.registry.core.Tag tag1 : tags) { // if tag has been found remove the tag,set the tag found // variable to true if (tagName.equals(tag1.getTagName())) { registry.removeTag(resourcePath, tagName); tagFound = true; } } if (tagFound) { // if tag deleted return Response.status(Response.Status.NO_CONTENT).build(); } else { log.debug("tag not found"); // if the specified tag is not found,returns http 404 return Response.status(Response.Status.NOT_FOUND).build(); } } catch (RegistryException e) { log.error("Failed to delete a tag " + tagName + " " + "on resource " + resourcePath, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } }
@Override public void delete(RequestContext requestContext) throws RegistryException { if (!CommonUtil.isUpdateLockAvailable()) { return; } CommonUtil.acquireUpdateLock(); try { Registry registry = requestContext.getRegistry(); ResourcePath resourcePath = requestContext.getResourcePath(); if (resourcePath == null) { throw new RegistryException("The resource path is not available."); } Resource resource = registry.get(resourcePath.getPath()); } finally { CommonUtil.releaseUpdateLock(); } }
private void fixAssociations( String path, String type, boolean isSource, boolean isTarget, Association[] toAdd) throws RegistryException { final String SEPARATOR = ":"; // Get the existing association list which is related to the current operation Set<String> existingSet = new HashSet<String>(); for (Association association : registry.getAllAssociations(path)) { if (type.equals(association.getAssociationType()) && ((isSource && association.getSourcePath().equals(path)) || (isTarget && association.getDestinationPath().equals(path)))) { existingSet.add( association.getSourcePath() + SEPARATOR + association.getDestinationPath() + SEPARATOR + association.getAssociationType()); } } // Get the updated association list from the projectGroup object Set<String> updatedSet = new HashSet<String>(); for (Association association : toAdd) { updatedSet.add( association.getSourcePath() + SEPARATOR + association.getDestinationPath() + SEPARATOR + association.getAssociationType()); } Set<String> removedAssociations = new HashSet<String>(existingSet); removedAssociations.removeAll(updatedSet); Set<String> newAssociations = new HashSet<String>(updatedSet); newAssociations.removeAll(existingSet); for (String removedAssociation : removedAssociations) { String[] params = removedAssociation.split(SEPARATOR); registry.removeAssociation(params[0], params[1], params[2]); } for (String newAssociation : newAssociations) { String[] params = newAssociation.split(SEPARATOR); registry.addAssociation(params[0], params[1], params[2]); } }
/** * This method add array of tags to the specified resource * * @param resourcePath - Resource path * @param tags - eg:{"tags":[<array of tag names>]} * @return HTTP 204 No Content ,if success. */ @POST @Consumes("application/json") @Produces("application/json") @ApiOperation( value = "Add an array of tags to a resource", httpMethod = "POST", notes = "Add an array of tags to a resource") @ApiResponses( value = { @ApiResponse(code = 204, message = "Resource tagged successfully"), @ApiResponse(code = 401, message = "Invalid credentials provided"), @ApiResponse(code = 404, message = "Specified resource not found"), @ApiResponse(code = 500, message = "Internal server error occurred") }) public Response addTags( @QueryParam("path") String resourcePath, TagModel tags, @HeaderParam("X-JWT-Assertion") String JWTToken) { RestAPIAuthContext authContext = RestAPISecurityUtils.getAuthContext( PrivilegedCarbonContext.getThreadLocalCarbonContext(), JWTToken); if (!authContext.isAuthorized()) { return Response.status(Response.Status.UNAUTHORIZED).build(); } try { Registry registry = getUserRegistry(authContext.getUserName(), authContext.getTenantId()); if (!registry.resourceExists(resourcePath)) { return Response.status(Response.Status.NOT_FOUND) .entity(RestAPIConstants.RESOURCE_NOT_FOUND) .build(); } String[] tagsOnResource = tags.getTags(); for (String aTagsOnResource : tagsOnResource) { registry.applyTag(resourcePath, aTagsOnResource); } return Response.status(Response.Status.NO_CONTENT).build(); } catch (RegistryException e) { log.error("user doesn't have permission to put the tags for the given resource", e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } }
public boolean removeDomainMappingFromRegistry(String actualHost) throws Exception { boolean successfullyRemoved; try { registry.beginTransaction(); String hostResourcePath = CartridgeConstants.DomainMappingInfo.HOSTINFO; if (registry.resourceExists(hostResourcePath)) { Resource hostResource = registry.get(hostResourcePath); Collection hostInfoCollection; if (hostResource instanceof Collection) { hostInfoCollection = (Collection) hostResource; } else { throw new Exception("Resource is not a collection " + hostResourcePath); } String[] paths = hostInfoCollection.getChildren(); for (String path : paths) { Resource domainMapping = registry.get(path); String actualHostInRegistry = domainMapping.getProperty(CartridgeConstants.DomainMappingInfo.ACTUAL_HOST); if (actualHostInRegistry != null && actualHost.equalsIgnoreCase(actualHostInRegistry)) { registry.delete(path); } } } registry.commitTransaction(); successfullyRemoved = true; } catch (RegistryException e) { registry.rollbackTransaction(); log.error("Unable to remove the mapping", e); throw e; } return successfullyRemoved; }
/** * This method is used to back up existing Files. * * @param registry registry instance. * @param path path of the rxt. * @param fileName file name of backed up rxt files. * @throws RegistryException */ public static void backUpFiles(Registry registry, String path, String fileName) throws RegistryException { Resource resource = registry.get(path); try { contentToFile(resource.getContentStream(), fileName); } catch (FileNotFoundException e) { System.out.println("Could not read file content"); } }