/** * 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; }
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]); } }
/** * Simulates a configSystemRegistry operation. * * <p>Operation criteria: get - path put - path, resourcePath (existing resource), optional : * mediaType resourceExists - path delete - path importResource - path, param1 (URL: source URL), * optional : mediaType copy - path, param1 (target path) move - path, param1 (target path) rename * - path, param1 (target path) removeLink - path createLink - path, param1 (target path), * optional : param2 (target sub-path) invokeAspect - path, param1 (aspect name), param2 (action) * addAssociation - path, param1 (target path), param2 (association type) removeAssociation - * path, param1 (target path), param2 (association type) getAssociations - path, param1 * (association type) getAllAssociations - path createVersion - path restoreVersion - path * getVersions - path applyTag - path, param1 (tag) removeTag - path, param1 (tag) getTags - path * getResourcePathsWithTag - param1 (tag) rateResource - path, param1 (Number: rating) getRating - * path, param1 (username) getAverageRating - path addComment - path, param1 (comment) * removeComment - path editComment - path, param1 (comment) getComments - path searchContent - * param1 (keywords) executeQuery - param1 (Map: parameters, ex:- key1:val1,key2:val2,...), * optional: path * * <p>Operations not-supported dump restore * * @param simulationRequest the simulation request. * @throws Exception if an exception occurs while executing any operation, or if an invalid * parameter was entered. */ public static void simulateRegistryOperation( Registry rootRegistry, SimulationRequest simulationRequest) throws Exception { String operation = simulationRequest.getOperation(); if (operation == null) { return; } if (operation.toLowerCase().equals("get")) { String path = simulationRequest.getPath(); if (isInvalidateValue(path)) { return; } simulationService.setSimulation(true); rootRegistry.get(path); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("resourceexists")) { String path = simulationRequest.getPath(); if (isInvalidateValue(path)) { return; } simulationService.setSimulation(true); rootRegistry.resourceExists(path); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("put")) { String path = simulationRequest.getPath(); String resourcePath = simulationRequest.getResourcePath(); String type = null; String[] params = simulationRequest.getParameters(); if (params != null && params.length >= 1) { type = params[0]; } if (isInvalidateValue(path) || isInvalidateValue(type)) { return; } Resource resource; if (!isInvalidateValue(resourcePath) && rootRegistry.resourceExists(resourcePath)) { resource = rootRegistry.get(resourcePath); } else if (type.toLowerCase().equals("collection")) { resource = rootRegistry.newCollection(); } else { resource = rootRegistry.newResource(); } simulationService.setSimulation(true); resource.setMediaType(simulationRequest.getMediaType()); rootRegistry.put(path, resource); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("delete")) { String path = simulationRequest.getPath(); if (isInvalidateValue(path)) { return; } simulationService.setSimulation(true); rootRegistry.delete(path); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("importresource")) { String path = simulationRequest.getPath(); String sourceURL = null; String[] params = simulationRequest.getParameters(); if (params != null && params.length >= 1) { sourceURL = params[0]; } if (isInvalidateValue(path) || isInvalidateValue(sourceURL)) { return; } simulationService.setSimulation(true); Resource resource = rootRegistry.newResource(); resource.setMediaType(simulationRequest.getMediaType()); rootRegistry.importResource(path, sourceURL, resource); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("rename")) { String path = simulationRequest.getPath(); String target = null; String[] params = simulationRequest.getParameters(); if (params != null && params.length >= 1) { target = params[0]; } if (isInvalidateValue(path) || isInvalidateValue(target)) { return; } simulationService.setSimulation(true); rootRegistry.rename(path, target); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("move")) { String path = simulationRequest.getPath(); String target = null; String[] params = simulationRequest.getParameters(); if (params != null && params.length >= 1) { target = params[0]; } if (isInvalidateValue(path) || isInvalidateValue(target)) { return; } simulationService.setSimulation(true); rootRegistry.move(path, target); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("copy")) { String path = simulationRequest.getPath(); String target = null; String[] params = simulationRequest.getParameters(); if (params != null && params.length >= 1) { target = params[0]; } if (isInvalidateValue(path) || isInvalidateValue(target)) { return; } simulationService.setSimulation(true); rootRegistry.copy(path, target); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("removelink")) { String path = simulationRequest.getPath(); if (isInvalidateValue(path)) { return; } simulationService.setSimulation(true); rootRegistry.removeLink(path); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("createlink")) { String path = simulationRequest.getPath(); String target = null; String targetSubPath = null; String[] params = simulationRequest.getParameters(); if (params != null && params.length > 0) { target = params[0]; if (params.length > 1) { targetSubPath = params[1]; } } if (isInvalidateValue(path) || isInvalidateValue(target)) { return; } simulationService.setSimulation(true); if (isInvalidateValue(targetSubPath)) { rootRegistry.createLink(path, target); } else { rootRegistry.createLink(path, target, targetSubPath); } simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("invokeaspect")) { String path = simulationRequest.getPath(); String aspectName = null; String action = null; String[] params = simulationRequest.getParameters(); if (params != null && params.length >= 2) { aspectName = params[0]; action = params[1]; } if (isInvalidateValue(path) || isInvalidateValue(aspectName) || isInvalidateValue(action)) { return; } simulationService.setSimulation(true); rootRegistry.invokeAspect(path, aspectName, action); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("addassociation")) { String path = simulationRequest.getPath(); String target = null; String associationType = null; String[] params = simulationRequest.getParameters(); if (params != null && params.length >= 2) { target = params[0]; associationType = params[1]; } if (isInvalidateValue(path) || isInvalidateValue(target) || isInvalidateValue(associationType)) { return; } simulationService.setSimulation(true); rootRegistry.addAssociation(path, target, associationType); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("removeassociation")) { String path = simulationRequest.getPath(); String target = null; String associationType = null; String[] params = simulationRequest.getParameters(); if (params != null && params.length >= 2) { target = params[0]; associationType = params[1]; } if (isInvalidateValue(path) || isInvalidateValue(target) || isInvalidateValue(associationType)) { return; } simulationService.setSimulation(true); rootRegistry.removeAssociation(path, target, associationType); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("getassociations")) { String path = simulationRequest.getPath(); String associationType = null; String[] params = simulationRequest.getParameters(); if (params != null && params.length >= 1) { associationType = params[0]; } if (isInvalidateValue(path) || isInvalidateValue(associationType)) { return; } simulationService.setSimulation(true); rootRegistry.getAssociations(path, associationType); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("getallassociations")) { String path = simulationRequest.getPath(); if (isInvalidateValue(path)) { return; } simulationService.setSimulation(true); rootRegistry.getAllAssociations(path); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("createversion")) { String path = simulationRequest.getPath(); if (isInvalidateValue(path)) { return; } simulationService.setSimulation(true); rootRegistry.createVersion(path); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("restoreversion")) { String path = simulationRequest.getPath(); if (isInvalidateValue(path)) { return; } simulationService.setSimulation(true); rootRegistry.restoreVersion(path); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("getversions")) { String path = simulationRequest.getPath(); if (isInvalidateValue(path)) { return; } simulationService.setSimulation(true); rootRegistry.getVersions(path); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("applytag")) { String path = simulationRequest.getPath(); String tag = null; String[] params = simulationRequest.getParameters(); if (params != null && params.length >= 1) { tag = params[0]; } if (isInvalidateValue(path) || isInvalidateValue(tag)) { return; } simulationService.setSimulation(true); rootRegistry.applyTag(path, tag); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("removetag")) { String path = simulationRequest.getPath(); String tag = null; String[] params = simulationRequest.getParameters(); if (params != null && params.length >= 1) { tag = params[0]; } if (isInvalidateValue(path) || isInvalidateValue(tag)) { return; } simulationService.setSimulation(true); rootRegistry.removeTag(path, tag); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("gettags")) { String path = simulationRequest.getPath(); if (isInvalidateValue(path)) { return; } simulationService.setSimulation(true); rootRegistry.getTags(path); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("getresourcepathswithtag")) { String tag = null; String[] params = simulationRequest.getParameters(); if (params != null && params.length >= 1) { tag = params[0]; } if (isInvalidateValue(tag)) { return; } simulationService.setSimulation(true); rootRegistry.getResourcePathsWithTag(tag); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("rateresource")) { String path = simulationRequest.getPath(); int rating = -1; String[] params = simulationRequest.getParameters(); if (params != null && params.length >= 1) { try { rating = Integer.parseInt(params[0]); } catch (NumberFormatException ignored) { return; } } if (isInvalidateValue(path) || rating == -1) { return; } simulationService.setSimulation(true); rootRegistry.rateResource(path, rating); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("getrating")) { String path = simulationRequest.getPath(); String username = null; String[] params = simulationRequest.getParameters(); if (params != null && params.length >= 1) { username = params[0]; } if (isInvalidateValue(path) || isInvalidateValue(username)) { return; } simulationService.setSimulation(true); rootRegistry.getRating(path, username); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("getaveragerating")) { String path = simulationRequest.getPath(); if (isInvalidateValue(path)) { return; } simulationService.setSimulation(true); rootRegistry.getAverageRating(path); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("addcomment")) { String path = simulationRequest.getPath(); String comment = null; String[] params = simulationRequest.getParameters(); if (params != null && params.length >= 1) { comment = params[0]; } if (isInvalidateValue(path) || isInvalidateValue(comment)) { return; } simulationService.setSimulation(true); rootRegistry.addComment(path, new Comment(comment)); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("editcomment")) { String path = simulationRequest.getPath(); String comment = null; String[] params = simulationRequest.getParameters(); if (params != null && params.length >= 1) { comment = params[0]; } if (isInvalidateValue(path) || isInvalidateValue(comment)) { return; } simulationService.setSimulation(true); rootRegistry.editComment(path, comment); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("removeComment")) { String path = simulationRequest.getPath(); if (isInvalidateValue(path)) { return; } simulationService.setSimulation(true); rootRegistry.removeComment(path); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("getcomments")) { String path = simulationRequest.getPath(); if (isInvalidateValue(path)) { return; } simulationService.setSimulation(true); rootRegistry.getComments(path); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("searchcontent")) { String keywords = null; String[] params = simulationRequest.getParameters(); if (params != null && params.length >= 1) { keywords = params[0]; } if (isInvalidateValue(keywords)) { return; } simulationService.setSimulation(true); rootRegistry.searchContent(keywords); simulationService.setSimulation(false); } else if (operation.toLowerCase().equals("executequery")) { String path = simulationRequest.getPath(); String queryParams = null; String[] params = simulationRequest.getParameters(); if (params != null && params.length >= 1) { queryParams = params[0]; } Map<String, String> paramMap = new LinkedHashMap<String, String>(); if (isInvalidateValue(queryParams)) { return; } String[] entries = queryParams.split(","); if (entries != null) { for (String entry : entries) { String[] keyValPair = entry.split(":"); if (keyValPair != null && keyValPair.length == 2) { paramMap.put(keyValPair[0], keyValPair[1]); } } } simulationService.setSimulation(true); rootRegistry.executeQuery(path, paramMap); simulationService.setSimulation(false); } else { throw new Exception("Unsupported Registry Operation: " + operation); } }
public String addWadlToRegistry( RequestContext requestContext, Resource resource, String resourcePath, boolean skipValidation) throws RegistryException { String wadlName = RegistryUtils.getResourceName(resourcePath); String version = requestContext.getResource().getProperty(RegistryConstants.VERSION_PARAMETER_NAME); if (version == null) { version = CommonConstants.WADL_VERSION_DEFAULT_VALUE; requestContext.getResource().setProperty(RegistryConstants.VERSION_PARAMETER_NAME, version); } OMElement wadlElement; String wadlContent; Object resourceContent = resource.getContent(); if (resourceContent instanceof String) { wadlContent = (String) resourceContent; } else { wadlContent = new String((byte[]) resourceContent); } try { XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(wadlContent)); StAXOMBuilder builder = new StAXOMBuilder(reader); wadlElement = builder.getDocumentElement(); } catch (XMLStreamException e) { // This exception is unexpected because the WADL already validated String msg = "Unexpected error occured " + "while reading the WADL at " + resourcePath + "."; log.error(msg); throw new RegistryException(msg, e); } String wadlNamespace = wadlElement.getNamespace().getNamespaceURI(); String namespaceSegment = CommonUtil.derivePathFragmentFromNamespace(wadlNamespace).replace("//", "/"); String actualPath = getChrootedWadlLocation(requestContext.getRegistryContext()) + namespaceSegment + version + "/" + wadlName; OMElement grammarsElement = wadlElement.getFirstChildWithName(new QName(wadlNamespace, "grammars")); if (StringUtils.isNotBlank(requestContext.getSourceURL())) { String uri = requestContext.getSourceURL(); if (!skipValidation) { validateWADL(uri); } if (resource.getUUID() == null) { resource.setUUID(UUID.randomUUID().toString()); } String wadlBaseUri = uri.substring(0, uri.lastIndexOf("/") + 1); if (grammarsElement != null) { // This is to avoid evaluating the grammars import when building AST grammarsElement.detach(); wadlElement.addChild(resolveImports(grammarsElement, wadlBaseUri, version)); } } else { if (!skipValidation) { File tempFile = null; BufferedWriter bufferedWriter = null; try { tempFile = File.createTempFile(wadlName, null); bufferedWriter = new BufferedWriter(new FileWriter(tempFile)); bufferedWriter.write(wadlElement.toString()); bufferedWriter.flush(); } catch (IOException e) { String msg = "Error occurred while reading the WADL File"; log.error(msg, e); throw new RegistryException(msg, e); } finally { if (bufferedWriter != null) { try { bufferedWriter.close(); } catch (IOException e) { String msg = "Error occurred while closing File writer"; log.warn(msg, e); } } } validateWADL(tempFile.toURI().toString()); try { delete(tempFile); } catch (IOException e) { String msg = "An error occurred while deleting the temporary files from local file system."; log.warn(msg, e); throw new RegistryException(msg, e); } } if (grammarsElement != null) { grammarsElement = resolveImports(grammarsElement, null, version); wadlElement.addChild(grammarsElement); } } requestContext.setResourcePath(new ResourcePath(actualPath)); if (resource.getProperty(CommonConstants.SOURCE_PROPERTY) == null) { resource.setProperty(CommonConstants.SOURCE_PROPERTY, CommonConstants.SOURCE_AUTO); } registry.put(actualPath, resource); addImportAssociations(actualPath); if (getCreateService()) { OMElement serviceElement = RESTServiceUtils.createRestServiceArtifact( wadlElement, wadlName, version, RegistryUtils.getRelativePath(requestContext.getRegistryContext(), actualPath)); String servicePath = RESTServiceUtils.addServiceToRegistry(requestContext, serviceElement); registry.addAssociation(servicePath, actualPath, CommonConstants.DEPENDS); registry.addAssociation(actualPath, servicePath, CommonConstants.USED_BY); String endpointPath = createEndpointElement(requestContext, wadlElement, version); if (endpointPath != null) { registry.addAssociation(servicePath, endpointPath, CommonConstants.DEPENDS); registry.addAssociation(endpointPath, servicePath, CommonConstants.USED_BY); } } return resource.getPath(); }
private void addDependency(String source, String target) throws RegistryException { registry.addAssociation(source, target, CommonConstants.DEPENDS); registry.addAssociation(target, source, CommonConstants.USED_BY); }
public void put(RequestContext requestContext) throws RegistryException { WSDLProcessor wsdl = null; if (!CommonUtil.isUpdateLockAvailable()) { return; } CommonUtil.acquireUpdateLock(); try { Registry registry = requestContext.getRegistry(); Resource resource = requestContext.getResource(); if (resource == null) { throw new RegistryException("The resource is not available."); } String originalServicePath = requestContext.getResourcePath().getPath(); String resourceName = RegistryUtils.getResourceName(originalServicePath); OMElement serviceInfoElement, previousServiceInfoElement = null; Object resourceContent = resource.getContent(); String serviceInfo; if (resourceContent instanceof String) { serviceInfo = (String) resourceContent; } else { serviceInfo = RegistryUtils.decodeBytes((byte[]) resourceContent); } try { XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(serviceInfo)); StAXOMBuilder builder = new StAXOMBuilder(reader); serviceInfoElement = builder.getDocumentElement(); } catch (Exception e) { String msg = "Error in parsing the service content of the service. " + "The requested path to store the service: " + originalServicePath + "."; log.error(msg); throw new RegistryException(msg, e); } // derive the service path that the service should be saved. String serviceName = CommonUtil.getServiceName(serviceInfoElement); String serviceNamespace = CommonUtil.getServiceNamespace(serviceInfoElement); String servicePath = ""; if (serviceInfoElement.getChildrenWithLocalName("newServicePath").hasNext()) { Iterator OmElementIterator = serviceInfoElement.getChildrenWithLocalName("newServicePath"); while (OmElementIterator.hasNext()) { OMElement next = (OMElement) OmElementIterator.next(); servicePath = next.getText(); break; } } else { if (registry.resourceExists(originalServicePath)) { // Fixing REGISTRY-1790. Save the Service to the given original // service path if there is a service already exists there servicePath = originalServicePath; } else { servicePath = RegistryUtils.getAbsolutePath( registry.getRegistryContext(), registry.getRegistryContext().getServicePath() + (serviceNamespace == null ? "" : CommonUtil.derivePathFragmentFromNamespace(serviceNamespace)) + serviceName); } } String serviceVersion = org.wso2.carbon.registry.common.utils.CommonUtil.getServiceVersion(serviceInfoElement); if (serviceVersion.length() == 0) { serviceVersion = defaultServiceVersion; CommonUtil.setServiceVersion(serviceInfoElement, serviceVersion); resource.setContent(serviceInfoElement.toString()); } // saving the artifact id. String serviceId = resource.getUUID(); if (serviceId == null) { // generate a service id serviceId = UUID.randomUUID().toString(); resource.setUUID(serviceId); } if (registry.resourceExists(servicePath)) { Resource oldResource = registry.get(servicePath); String oldContent; Object content = oldResource.getContent(); if (content instanceof String) { oldContent = (String) content; } else { oldContent = RegistryUtils.decodeBytes((byte[]) content); } OMElement oldServiceInfoElement = null; if (serviceInfo.equals(oldContent)) { // TODO: This needs a better solution. This fix was put in place to avoid // duplication of services under /_system/governance, when no changes were made. // However, the fix is not perfect and needs to be rethought. Perhaps the logic // below can be reshaped a bit, or may be we don't need to compare the // difference over here with a little fix to the Governance API end. - Janaka. // We have fixed this assuming that the temp path where services are stored is under // /_system/governance/[serviceName] // Hence if we are to change that location, then we need to change the following code // segment as well String tempPath = RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + RegistryConstants.PATH_SEPARATOR + resourceName; if (!originalServicePath.equals(tempPath)) { String path = RegistryUtils.getRelativePathToOriginal( servicePath, RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH); ArtifactManager.getArtifactManager().getTenantArtifactRepository().addArtifact(path); return; } requestContext.setProcessingComplete(true); return; } if ("true".equals(resource.getProperty("registry.DefinitionImport"))) { resource.removeProperty("registry.DefinitionImport"); try { XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(oldContent)); StAXOMBuilder builder = new StAXOMBuilder(reader); oldServiceInfoElement = builder.getDocumentElement(); CommonUtil.setServiceName( oldServiceInfoElement, CommonUtil.getServiceName(serviceInfoElement)); CommonUtil.setServiceNamespace( oldServiceInfoElement, CommonUtil.getServiceNamespace(serviceInfoElement)); CommonUtil.setDefinitionURL( oldServiceInfoElement, CommonUtil.getDefinitionURL(serviceInfoElement)); CommonUtil.setEndpointEntries( oldServiceInfoElement, CommonUtil.getEndpointEntries(serviceInfoElement)); CommonUtil.setServiceVersion( oldServiceInfoElement, org.wso2.carbon.registry.common.utils.CommonUtil.getServiceVersion( serviceInfoElement)); serviceInfoElement = oldServiceInfoElement; resource.setContent(serviceInfoElement.toString()); resource.setDescription(oldResource.getDescription()); } catch (Exception e) { String msg = "Error in parsing the service content of the service. " + "The requested path to store the service: " + originalServicePath + "."; log.error(msg); throw new RegistryException(msg, e); } } try { previousServiceInfoElement = AXIOMUtil.stringToOM(oldContent); } catch (XMLStreamException e) { String msg = "Error in parsing the service content of the service. " + "The requested path to store the service: " + originalServicePath + "."; log.error(msg); throw new RegistryException(msg, e); } } else if ("true".equals(resource.getProperty("registry.DefinitionImport"))) { resource.removeProperty("registry.DefinitionImport"); } // CommonUtil.addGovernanceArtifactEntryWithAbsoluteValues( // CommonUtil.getUnchrootedSystemRegistry(requestContext), // serviceId, servicePath); String definitionURL = CommonUtil.getDefinitionURL(serviceInfoElement); if (previousServiceInfoElement != null) { String oldDefinition = CommonUtil.getDefinitionURL(previousServiceInfoElement); if ((!"".equals(oldDefinition) && "".equals(definitionURL)) || (!"".endsWith(oldDefinition) && !oldDefinition.equals(definitionURL))) { try { registry.removeAssociation(servicePath, oldDefinition, CommonConstants.DEPENDS); registry.removeAssociation(oldDefinition, servicePath, CommonConstants.USED_BY); EndpointUtils.removeEndpointEntry(oldDefinition, serviceInfoElement, registry); resource.setContent( RegistryUtils.decodeBytes((serviceInfoElement.toString()).getBytes())); } catch (RegistryException e) { throw new RegistryException( "Failed to remove endpoints from Service UI : " + serviceName, e); } } } boolean alreadyAdded = false; if (definitionURL != null && (definitionURL.startsWith("http://") || definitionURL.startsWith("https://"))) { String definitionPath; if (definitionURL.toLowerCase().endsWith("wsdl")) { wsdl = buildWSDLProcessor(requestContext); RequestContext context = new RequestContext( registry, requestContext.getRepository(), requestContext.getVersionRepository()); context.setResourcePath( new ResourcePath(RegistryConstants.PATH_SEPARATOR + serviceName + ".wsdl")); context.setSourceURL(definitionURL); context.setResource(new ResourceImpl()); definitionPath = wsdl.addWSDLToRegistry( context, definitionURL, null, false, false, disableWSDLValidation, disableSymlinkCreation); } else if (definitionURL.toLowerCase().endsWith("wadl")) { WADLProcessor wadlProcessor = buildWADLProcessor(requestContext); wadlProcessor.setCreateService(false); RequestContext context = new RequestContext( registry, requestContext.getRepository(), requestContext.getVersionRepository()); context.setResourcePath( new ResourcePath(RegistryConstants.PATH_SEPARATOR + serviceName + ".wadl")); context.setSourceURL(definitionURL); context.setResource(new ResourceImpl()); definitionPath = wadlProcessor.importWADLToRegistry(context, null, disableWADLValidation); } else { throw new RegistryException( "Invalid service definition found. " + "Please enter a valid WSDL/WADL URL"); } if (definitionPath == null) { return; } definitionURL = RegistryUtils.getRelativePath(requestContext.getRegistryContext(), definitionPath); CommonUtil.setDefinitionURL(serviceInfoElement, definitionURL); resource.setContent(RegistryUtils.decodeBytes((serviceInfoElement.toString()).getBytes())); // updating the wsdl/wadl url ((ResourceImpl) resource).prepareContentForPut(); persistServiceResource(registry, resource, servicePath); alreadyAdded = true; // and make the associations registry.addAssociation(servicePath, definitionPath, CommonConstants.DEPENDS); registry.addAssociation(definitionPath, servicePath, CommonConstants.USED_BY); } else if (definitionURL != null && definitionURL.startsWith(RegistryConstants.ROOT_PATH)) { // it seems definitionUrl is a registry path.. String definitionPath = RegistryUtils.getAbsolutePath(requestContext.getRegistryContext(), definitionURL); if (!definitionPath.startsWith( RegistryUtils.getAbsolutePath( requestContext.getRegistryContext(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH))) { definitionPath = RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + definitionPath; } boolean addItHere = false; if (!registry.resourceExists(definitionPath)) { String msg = "Associating service to a non-existing WSDL. wsdl url: " + definitionPath + ", " + "service path: " + servicePath + "."; log.error(msg); throw new RegistryException(msg); } if (!registry.resourceExists(servicePath)) { addItHere = true; } else { Association[] dependencies = registry.getAssociations(servicePath, CommonConstants.DEPENDS); boolean dependencyFound = false; if (dependencies != null) { for (Association dependency : dependencies) { if (definitionPath.equals(dependency.getDestinationPath())) { dependencyFound = true; } } } if (!dependencyFound) { addItHere = true; } } if (addItHere) { // add the service right here.. ((ResourceImpl) resource).prepareContentForPut(); persistServiceResource(registry, resource, servicePath); alreadyAdded = true; // and make the associations registry.addAssociation(servicePath, definitionPath, CommonConstants.DEPENDS); registry.addAssociation(definitionPath, servicePath, CommonConstants.USED_BY); } } if (!alreadyAdded) { // we are adding the resource anyway. ((ResourceImpl) resource).prepareContentForPut(); persistServiceResource(registry, resource, servicePath); } /* if (!servicePath.contains(registry.getRegistryContext().getServicePath())) { if (defaultEnvironment == null) { String serviceDefaultEnvironment = registry.getRegistryContext().getServicePath(); String relativePath = serviceDefaultEnvironment.replace(RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH, ""); relativePath = relativePath.replace(CommonUtil.derivePathFragmentFromNamespace(serviceNamespace),""); defaultEnvironment = relativePath; } String currentRelativePath = servicePath.substring(0, servicePath.indexOf(CommonUtil.derivePathFragmentFromNamespace(serviceNamespace))); currentRelativePath = currentRelativePath.replace(RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH,""); String endpointEnv = EndpointUtils.getEndpointLocation(); String[] pathSegments = defaultEnvironment.split(RegistryConstants.PATH_SEPARATOR); for (String pathSegment : pathSegments) { endpointEnv = endpointEnv.replace(pathSegment,""); currentRelativePath = currentRelativePath.replace(pathSegment,""); } while(endpointEnv.startsWith(RegistryConstants.PATH_SEPARATOR)){ endpointEnv = endpointEnv.replaceFirst(RegistryConstants.PATH_SEPARATOR,""); } environment = currentRelativePath + endpointEnv; } */ EndpointUtils.saveEndpointsFromServices( servicePath, serviceInfoElement, registry, CommonUtil.getUnchrootedSystemRegistry(requestContext)); String symlinkLocation = RegistryUtils.getAbsolutePath( requestContext.getRegistryContext(), requestContext.getResource().getProperty(RegistryConstants.SYMLINK_PROPERTY_NAME)); if (!servicePath.equals(originalServicePath)) { // we are creating a sym link from service path to original service path. Resource serviceResource = requestContext.getRegistry().get(RegistryUtils.getParentPath(originalServicePath)); String isLink = serviceResource.getProperty("registry.link"); String mountPoint = serviceResource.getProperty("registry.mountpoint"); String targetPoint = serviceResource.getProperty("registry.targetpoint"); String actualPath = serviceResource.getProperty("registry.actualpath"); if (isLink != null && mountPoint != null && targetPoint != null) { symlinkLocation = actualPath + RegistryConstants.PATH_SEPARATOR; } if (symlinkLocation != null) { requestContext .getSystemRegistry() .createLink(symlinkLocation + resourceName, servicePath); } } // in this flow the resource is already added. marking the process completed.. requestContext.setProcessingComplete(true); if (wsdl != null && CommonConstants.ENABLE.equals( System.getProperty(CommonConstants.UDDI_SYSTEM_PROPERTY))) { AuthToken authToken = UDDIUtil.getPublisherAuthToken(); if (authToken == null) { return; } // creating the business service info bean BusinessServiceInfo businessServiceInfo = new BusinessServiceInfo(); // Following lines removed for fixing REGISTRY-1898. // businessServiceInfo.setServiceName(serviceName.trim()); // businessServiceInfo.setServiceNamespace(serviceNamespace.trim()); // // businessServiceInfo.setServiceEndpoints(CommonUtil.getEndpointEntries(serviceInfoElement)); // // businessServiceInfo.setDocuments(CommonUtil.getDocLinks(serviceInfoElement)); businessServiceInfo.setServiceDescription( CommonUtil.getServiceDescription(serviceInfoElement)); WSDLInfo wsdlInfo = wsdl.getMasterWSDLInfo(); businessServiceInfo.setServiceWSDLInfo(wsdlInfo); UDDIPublisher publisher = new UDDIPublisher(); publisher.publishBusinessService(authToken, businessServiceInfo); } String path = RegistryUtils.getRelativePathToOriginal( servicePath, RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH); ArtifactManager.getArtifactManager().getTenantArtifactRepository().addArtifact(path); } finally { CommonUtil.releaseUpdateLock(); } }
/** * Saves the swagger file as a registry artifact. * * @param inputStream input stream to read content. * @param commonLocation root location of the swagger artifacts. * @param sourceUrl source URL. * @throws RegistryException If a failure occurs when adding the swagger to registry. */ public boolean processSwagger(InputStream inputStream, String commonLocation, String sourceUrl) throws RegistryException { // create a collection if not exists. createCollection(commonLocation); // Reading resource content and content details. ByteArrayOutputStream swaggerContentStream = CommonUtil.readSourceContent(inputStream); JsonObject swaggerDocObject = getSwaggerObject(swaggerContentStream.toString()); String swaggerVersion = getSwaggerVersion(swaggerDocObject); documentVersion = requestContext.getResource().getProperty(RegistryConstants.VERSION_PARAMETER_NAME); if (documentVersion == null) { documentVersion = CommonConstants.SWAGGER_DOC_VERSION_DEFAULT_VALUE; requestContext .getResource() .setProperty(RegistryConstants.VERSION_PARAMETER_NAME, documentVersion); } String swaggerResourcePath = getSwaggerDocumentPath(commonLocation, swaggerDocObject); /* Switches from the swagger version and process document adding process and the REST Service creation process using the relevant documents. */ if (SwaggerConstants.SWAGGER_VERSION_12.equals(swaggerVersion)) { if (addSwaggerDocumentToRegistry( swaggerContentStream, swaggerResourcePath, documentVersion)) { List<JsonObject> resourceObjects = addResourceDocsToRegistry(swaggerDocObject, sourceUrl, swaggerResourcePath); restServiceElement = (resourceObjects != null) ? RESTServiceUtils.createRestServiceArtifact( swaggerDocObject, swaggerVersion, endpointUrl, resourceObjects, swaggerResourcePath, documentVersion) : null; } else { return false; } } else if (SwaggerConstants.SWAGGER_VERSION_2.equals(swaggerVersion)) { if (addSwaggerDocumentToRegistry( swaggerContentStream, swaggerResourcePath, documentVersion)) { createEndpointElement(swaggerDocObject, swaggerVersion); restServiceElement = RESTServiceUtils.createRestServiceArtifact( swaggerDocObject, swaggerVersion, endpointUrl, null, swaggerResourcePath, documentVersion); } else { return false; } } /* If REST Service content is not empty, saves the REST service and adds the relevant associations. */ if (restServiceElement != null) { String servicePath = RESTServiceUtils.addServiceToRegistry(requestContext, restServiceElement); registry.addAssociation(servicePath, swaggerResourcePath, CommonConstants.DEPENDS); registry.addAssociation(swaggerResourcePath, servicePath, CommonConstants.USED_BY); if (endpointUrl != null) { String endpointPath = RESTServiceUtils.addEndpointToRegistry( requestContext, endpointElement, endpointLocation); registry.addAssociation(servicePath, endpointPath, CommonConstants.DEPENDS); registry.addAssociation(endpointPath, servicePath, CommonConstants.USED_BY); } } else { log.warn("Service content is null. Cannot create the REST Service artifact."); } CommonUtil.closeOutputStream(swaggerContentStream); return true; }