Search in sources :

Example 31 with PACKAGE

use of org.wso2.ballerinalang.compiler.codegen.CodeGenerator.VariableIndex.Kind.PACKAGE in project carbon-business-process by wso2.

the class TenantRepository method undeploy.

/**
 * Undeploys a BPMN package.
 * This may be called by the BPMN deployer, when a BPMN package is deleted from the deployment folder or by admin services
 *
 * @param deploymentName package name to be undeployed
 * @param force          forceful deletion of package
 */
// public void undeploy(String deploymentName, boolean force) {
// 
// DeploymentMetaDataModel deploymentMetaDataModel;
// SqlSession sqlSession = null;
// try {
// // Remove the deployment from the tenant's registry
// deploymentMetaDataModel = activitiDAO
// .selectTenantAwareDeploymentModel(tenantId.toString(), deploymentName);
// 
// if ((deploymentMetaDataModel == null) && !force) {
// String msg = "Deployment: " + deploymentName + " does not exist.";
// log.warn(msg);
// return;
// }
// 
// ProcessEngineImpl engine = (ProcessEngineImpl) BPMNServerHolder.getInstance().getEngine();
// 
// DbSqlSessionFactory dbSqlSessionFactory =
// (DbSqlSessionFactory) engine.getProcessEngineConfiguration().
// getSessionFactories().get(DbSqlSession.class);
// 
// SqlSessionFactory sqlSessionFactory = dbSqlSessionFactory.getSqlSessionFactory();
// sqlSession = sqlSessionFactory.openSession();
// DeploymentMapper deploymentMapper = sqlSession.getMapper(DeploymentMapper.class);
// int rowCount = deploymentMapper.deleteDeploymentMetaData(deploymentMetaDataModel);
// 
// if (log.isDebugEnabled()) {
// log.debug("Total row count deleted=" + rowCount);
// }
// 
// // Remove the deployment archive from the tenant's deployment folder
// File deploymentArchive = new File(repoFolder, deploymentName + ".bar");
// FileUtils.deleteQuietly(deploymentArchive);
// 
// // Delete all versions of this package from the Activiti engine.
// RepositoryService repositoryService = engine.getRepositoryService();
// List<Deployment> deployments = repositoryService.createDeploymentQuery().deploymentTenantId(tenantId.toString()).
// deploymentName(deploymentName).list();
// for (Deployment deployment : deployments) {
// repositoryService.deleteDeployment(deployment.getId());
// }
// 
// //commit metadata
// sqlSession.commit();
// } finally {
// if (sqlSession != null) {
// sqlSession.close();
// }
// }
// 
// }
public void undeploy(String deploymentName, boolean force) throws BPSFault {
    try {
        // Remove the deployment from the tenant's registry
        RegistryService registryService = BPMNServerHolder.getInstance().getRegistryService();
        Registry tenantRegistry = registryService.getConfigSystemRegistry(tenantId);
        String deploymentRegistryPath = BPMNConstants.BPMN_REGISTRY_PATH + BPMNConstants.REGISTRY_PATH_SEPARATOR + deploymentName;
        if (!tenantRegistry.resourceExists(deploymentRegistryPath) && !force) {
            String msg = "Deployment: " + deploymentName + " does not exist.";
            log.warn(msg);
            return;
        }
        tenantRegistry.delete(deploymentRegistryPath);
        // Remove the deployment archive from the tenant's deployment folder
        File deploymentArchive = new File(repoFolder, deploymentName + ".bar");
        FileUtils.deleteQuietly(deploymentArchive);
        // Delete all versions of this package from the Activiti engine.
        ProcessEngine engine = BPMNServerHolder.getInstance().getEngine();
        RepositoryService repositoryService = engine.getRepositoryService();
        List<Deployment> deployments = repositoryService.createDeploymentQuery().deploymentTenantId(tenantId.toString()).deploymentName(deploymentName).list();
        for (Deployment deployment : deployments) {
            repositoryService.deleteDeployment(deployment.getId(), true);
        }
    } catch (RegistryException e) {
        String msg = "Failed to undeploy BPMN deployment: " + deploymentName + " for tenant: " + tenantId;
        log.error(msg, e);
        throw new BPSFault(msg, e);
    }
}
Also used : BPSFault(org.wso2.carbon.bpmn.core.BPSFault) Deployment(org.activiti.engine.repository.Deployment) Registry(org.wso2.carbon.registry.api.Registry) RegistryService(org.wso2.carbon.registry.api.RegistryService) File(java.io.File) RegistryException(org.wso2.carbon.registry.api.RegistryException) ProcessEngine(org.activiti.engine.ProcessEngine) RepositoryService(org.activiti.engine.RepositoryService)

Example 32 with PACKAGE

use of org.wso2.ballerinalang.compiler.codegen.CodeGenerator.VariableIndex.Kind.PACKAGE in project ballerina by ballerina-lang.

the class BallerinaParserService method validateAndParse.

/**
 * Validates a given ballerina input.
 *
 * @param bFileRequest - Object which holds data about Ballerina content.
 * @return List of errors if any
 */
private JsonObject validateAndParse(BFile bFileRequest) throws InvocationTargetException, IllegalAccessException {
    final java.nio.file.Path filePath = Paths.get(bFileRequest.getFilePath(), bFileRequest.getFileName());
    final String fileName = bFileRequest.getFileName();
    final String content = bFileRequest.getContent();
    BallerinaFile bFile = ParserUtils.compile(content, filePath);
    String programDir = TextDocumentServiceUtil.getSourceRoot(filePath);
    final BLangPackage model = bFile.getBLangPackage();
    final List<Diagnostic> diagnostics = bFile.getDiagnostics();
    ErrorCategory errorCategory = ErrorCategory.NONE;
    if (!diagnostics.isEmpty()) {
        if (model == null) {
            errorCategory = ErrorCategory.SYNTAX;
        } else {
            errorCategory = ErrorCategory.SEMANTIC;
        }
    }
    JsonArray errors = new JsonArray();
    final String errorCategoryName = errorCategory.name();
    diagnostics.forEach(diagnostic -> {
        JsonObject error = new JsonObject();
        Diagnostic.DiagnosticPosition position = diagnostic.getPosition();
        if (position != null) {
            if (!diagnostic.getSource().getCompilationUnitName().equals(fileName)) {
                return;
            }
            error.addProperty("row", position.getStartLine());
            error.addProperty("column", position.getStartColumn());
            error.addProperty("type", "error");
            error.addProperty("category", errorCategoryName);
        } else {
            // position == null means it's a bug in core side.
            error.addProperty("category", ErrorCategory.RUNTIME.name());
        }
        error.addProperty("text", diagnostic.getMessage());
        errors.add(error);
    });
    JsonObject result = new JsonObject();
    result.add("errors", errors);
    Gson gson = new Gson();
    JsonElement diagnosticsJson = gson.toJsonTree(diagnostics);
    result.add("diagnostics", diagnosticsJson);
    if (model != null && bFileRequest.needTree()) {
        BLangCompilationUnit compilationUnit = model.getCompilationUnits().stream().filter(compUnit -> fileName.equals(compUnit.getName())).findFirst().get();
        JsonElement modelElement = generateJSON(compilationUnit, new HashMap<>());
        result.add("model", modelElement);
    }
    final Map<String, ModelPackage> modelPackage = new HashMap<>();
    ParserUtils.loadPackageMap("Current Package", bFile.getBLangPackage(), modelPackage);
    Optional<ModelPackage> packageInfoJson = modelPackage.values().stream().findFirst();
    if (packageInfoJson.isPresent() && bFileRequest.needPackageInfo()) {
        JsonElement packageInfo = gson.toJsonTree(packageInfoJson.get());
        result.add("packageInfo", packageInfo);
    }
    if (programDir != null) {
        result.addProperty("programDirPath", programDir);
    }
    return result;
}
Also used : BallerinaFile(org.ballerinalang.composer.service.ballerina.parser.service.model.BallerinaFile) HashMap(java.util.HashMap) Diagnostic(org.ballerinalang.util.diagnostic.Diagnostic) JsonObject(com.google.gson.JsonObject) Gson(com.google.gson.Gson) JsonArray(com.google.gson.JsonArray) BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) JsonElement(com.google.gson.JsonElement) ModelPackage(org.ballerinalang.composer.service.ballerina.parser.service.model.lang.ModelPackage) BLangCompilationUnit(org.wso2.ballerinalang.compiler.tree.BLangCompilationUnit)

Example 33 with PACKAGE

use of org.wso2.ballerinalang.compiler.codegen.CodeGenerator.VariableIndex.Kind.PACKAGE in project ballerina by ballerina-lang.

the class CommandUtil method getCommandsByDiagnostic.

/**
 * Get the command instances for a given diagnostic.
 * @param diagnostic        Diagnostic to get the command against
 * @param params            Code Action parameters
 * @param lsPackageCache    Lang Server Package cache
 * @return  {@link List}    List of commands related to the given diagnostic
 */
public static List<Command> getCommandsByDiagnostic(Diagnostic diagnostic, CodeActionParams params, LSPackageCache lsPackageCache) {
    String diagnosticMessage = diagnostic.getMessage();
    List<Command> commands = new ArrayList<>();
    if (isUndefinedPackage(diagnosticMessage)) {
        String packageAlias = diagnosticMessage.substring(diagnosticMessage.indexOf("'") + 1, diagnosticMessage.lastIndexOf("'"));
        LSDocument sourceDocument = new LSDocument(params.getTextDocument().getUri());
        Path openedPath = CommonUtil.getPath(sourceDocument);
        String sourceRoot = TextDocumentServiceUtil.getSourceRoot(openedPath);
        sourceDocument.setSourceRoot(sourceRoot);
        lsPackageCache.getPackageMap().entrySet().stream().filter(pkgEntry -> {
            String fullPkgName = pkgEntry.getValue().packageID.orgName.getValue() + "/" + pkgEntry.getValue().packageID.getName().getValue();
            return fullPkgName.endsWith("." + packageAlias) || fullPkgName.endsWith("/" + packageAlias);
        }).forEach(pkgEntry -> {
            PackageID packageID = pkgEntry.getValue().packageID;
            String commandTitle = CommandConstants.IMPORT_PKG_TITLE + " " + packageID.getName().toString();
            String fullPkgName = packageID.getOrgName() + "/" + packageID.getName().getValue();
            CommandArgument pkgArgument = new CommandArgument(CommandConstants.ARG_KEY_PKG_NAME, fullPkgName);
            CommandArgument docUriArgument = new CommandArgument(CommandConstants.ARG_KEY_DOC_URI, params.getTextDocument().getUri());
            commands.add(new Command(commandTitle, CommandConstants.CMD_IMPORT_PACKAGE, new ArrayList<>(Arrays.asList(pkgArgument, docUriArgument))));
        });
    }
    return commands;
}
Also used : Path(java.nio.file.Path) CommonUtil(org.ballerinalang.langserver.common.utils.CommonUtil) Arrays(java.util.Arrays) BLangVariable(org.wso2.ballerinalang.compiler.tree.BLangVariable) CommandConstants(org.ballerinalang.langserver.common.constants.CommandConstants) Diagnostic(org.eclipse.lsp4j.Diagnostic) ArrayList(java.util.ArrayList) CodeActionParams(org.eclipse.lsp4j.CodeActionParams) LSDocument(org.ballerinalang.langserver.common.LSDocument) BLangResource(org.wso2.ballerinalang.compiler.tree.BLangResource) DocTag(org.ballerinalang.model.elements.DocTag) Locale(java.util.Locale) TopLevelNode(org.ballerinalang.model.tree.TopLevelNode) DiagnosticPos(org.wso2.ballerinalang.compiler.util.diagnotic.DiagnosticPos) Path(java.nio.file.Path) BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) BLangObject(org.wso2.ballerinalang.compiler.tree.BLangObject) PackageID(org.ballerinalang.model.elements.PackageID) FunctionNode(org.ballerinalang.model.tree.FunctionNode) LSPackageCache(org.ballerinalang.langserver.LSPackageCache) BLangFunction(org.wso2.ballerinalang.compiler.tree.BLangFunction) BLangAnnotationAttachment(org.wso2.ballerinalang.compiler.tree.BLangAnnotationAttachment) BLangTransformer(org.wso2.ballerinalang.compiler.tree.BLangTransformer) TextDocumentServiceUtil(org.ballerinalang.langserver.TextDocumentServiceUtil) BLangService(org.wso2.ballerinalang.compiler.tree.BLangService) List(java.util.List) BLangEnum(org.wso2.ballerinalang.compiler.tree.BLangEnum) Command(org.eclipse.lsp4j.Command) BEndpointVarSymbol(org.wso2.ballerinalang.compiler.semantics.model.symbols.BEndpointVarSymbol) BLangStruct(org.wso2.ballerinalang.compiler.tree.BLangStruct) Collections(java.util.Collections) Command(org.eclipse.lsp4j.Command) LSDocument(org.ballerinalang.langserver.common.LSDocument) ArrayList(java.util.ArrayList) PackageID(org.ballerinalang.model.elements.PackageID)

Example 34 with PACKAGE

use of org.wso2.ballerinalang.compiler.codegen.CodeGenerator.VariableIndex.Kind.PACKAGE in project ballerina by ballerina-lang.

the class ParserUtils method getAllPackages.

/**
 * Get All Native Packages.
 *
 * @return {@link Map} Package name, package functions and connectors
 */
public static Map<String, ModelPackage> getAllPackages() {
    final Map<String, ModelPackage> modelPackage = new HashMap<>();
    // TODO: remove once the packerina api for package listing is available
    final String[] packageNames = { "net.http", "net.http.authadaptor", "net.http.endpoints", "net.http.mock", "net.http.swagger", "net.uri", "mime", "net.websub", "net.websub.hub", "net.grpc", "auth", "auth.authz", "auth.authz.permissionstore", "auth.basic", "auth.jwtAuth", "auth.userstore", "auth.utils", "caching", "collections", "config", "data.sql", "file", "internal", "io", "jwt", "jwt.signature", "log", "math", "os", "reflect", "runtime", "security.crypto", "task", "time", "transactions.coordinator", "user", "util" };
    try {
        List<BLangPackage> builtInPackages = LSPackageLoader.getBuiltinPackages();
        for (BLangPackage bLangPackage : builtInPackages) {
            loadPackageMap(bLangPackage.packageID.getName().getValue(), bLangPackage, modelPackage);
        }
        CompilerContext context = CommonUtil.prepareTempCompilerContext();
        for (String packageName : packageNames) {
            PackageID packageID = new PackageID(new Name("ballerina"), new Name(packageName), new Name("0.0.0"));
            BLangPackage bLangPackage = LSPackageLoader.getPackageById(context, packageID);
            loadPackageMap(bLangPackage.packageID.getName().getValue(), bLangPackage, modelPackage);
        }
    } catch (Exception e) {
        // Above catch is to fail safe composer front end due to core errors.
        logger.warn("Error while loading packages");
    }
    return modelPackage;
}
Also used : BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) HashMap(java.util.HashMap) CompilerContext(org.wso2.ballerinalang.compiler.util.CompilerContext) ModelPackage(org.ballerinalang.composer.service.ballerina.parser.service.model.lang.ModelPackage) PackageID(org.ballerinalang.model.elements.PackageID) IOException(java.io.IOException) Name(org.wso2.ballerinalang.compiler.util.Name)

Example 35 with PACKAGE

use of org.wso2.ballerinalang.compiler.codegen.CodeGenerator.VariableIndex.Kind.PACKAGE in project ballerina by ballerina-lang.

the class ParserUtils method removeConstructsOfFile.

/**
 * Remove constructs from given file in given package from given package map.
 *
 * @param pkgName    Name of the package
 * @param fileName   Name of the File
 * @param packageMap Package constructs map
 */
public static void removeConstructsOfFile(String pkgName, String fileName, Map<String, ModelPackage> packageMap) {
    ModelPackage newPkg = new ModelPackage();
    newPkg.setName(pkgName);
    if (packageMap.containsKey(pkgName)) {
        ModelPackage currentPkg = packageMap.get(pkgName);
        currentPkg.getFunctions().forEach((Function func) -> {
            if (!func.getFileName().equals(fileName)) {
                newPkg.addFunctionsItem(func);
            }
        });
        currentPkg.getStructs().forEach((Struct struct) -> {
            if (!struct.getFileName().equals(fileName)) {
                newPkg.addStructsItem(struct);
            }
        });
        currentPkg.getAnnotations().forEach((AnnotationDef annotation) -> {
            if (!annotation.getFileName().equals(fileName)) {
                newPkg.addAnnotationsItem(annotation);
            }
        });
        currentPkg.getConnectors().forEach((Connector connector) -> {
            if (!connector.getFileName().equals(fileName)) {
                newPkg.addConnectorsItem(connector);
            }
        });
        packageMap.remove(pkgName);
        packageMap.put(pkgName, newPkg);
    }
}
Also used : Function(org.ballerinalang.composer.service.ballerina.parser.service.model.lang.Function) BLangFunction(org.wso2.ballerinalang.compiler.tree.BLangFunction) Connector(org.ballerinalang.composer.service.ballerina.parser.service.model.lang.Connector) BLangConnector(org.wso2.ballerinalang.compiler.tree.BLangConnector) ModelPackage(org.ballerinalang.composer.service.ballerina.parser.service.model.lang.ModelPackage) Struct(org.ballerinalang.composer.service.ballerina.parser.service.model.lang.Struct) BLangStruct(org.wso2.ballerinalang.compiler.tree.BLangStruct) AnnotationDef(org.ballerinalang.composer.service.ballerina.parser.service.model.lang.AnnotationDef)

Aggregations

BLangPackage (org.wso2.ballerinalang.compiler.tree.BLangPackage)49 ArrayList (java.util.ArrayList)34 Test (org.testng.annotations.Test)29 Page (org.ballerinalang.docgen.model.Page)18 File (java.io.File)16 CompilerContext (org.wso2.ballerinalang.compiler.util.CompilerContext)16 IOException (java.io.IOException)15 Path (java.nio.file.Path)13 List (java.util.List)13 BLangStruct (org.wso2.ballerinalang.compiler.tree.BLangStruct)11 PackageID (org.ballerinalang.model.elements.PackageID)10 Compiler (org.wso2.ballerinalang.compiler.Compiler)10 BLangFunction (org.wso2.ballerinalang.compiler.tree.BLangFunction)10 CompilerOptions (org.wso2.ballerinalang.compiler.util.CompilerOptions)10 Collectors (java.util.stream.Collectors)9 Arrays (java.util.Arrays)8 CompilerPhase (org.ballerinalang.compiler.CompilerPhase)7 BInvokableSymbol (org.wso2.ballerinalang.compiler.semantics.model.symbols.BInvokableSymbol)6 BPackageSymbol (org.wso2.ballerinalang.compiler.semantics.model.symbols.BPackageSymbol)6 BLangNode (org.wso2.ballerinalang.compiler.tree.BLangNode)6