Search in sources :

Example 41 with Names

use of org.wso2.ballerinalang.compiler.util.Names in project ballerina by ballerina-lang.

the class BallerinaDocGenerator method generateApiDocs.

/**
 * API to generate Ballerina API documentation.
 *
 * @param output        path to the output directory where the API documentation will be written to.
 * @param packageFilter comma separated list of package names to be filtered from the documentation.
 * @param isNative      whether the given packages are native or not.
 * @param sources       either the path to the directories where Ballerina source files reside or a
 *                      path to a Ballerina file which does not belong to a package.
 */
public static void generateApiDocs(String output, String packageFilter, boolean isNative, String... sources) {
    out.println("docerina: API documentation generation for sources - " + Arrays.toString(sources));
    for (String source : sources) {
        source = source.trim();
        try {
            Map<String, BLangPackage> docsMap;
            if (source.endsWith(".bal")) {
                Path sourceFilePath = Paths.get(source);
                Path parentDir = sourceFilePath.getParent();
                Path fileName = sourceFilePath.getFileName();
                if (fileName == null) {
                    log.warn("Skipping the source generation for invalid path: " + sourceFilePath);
                    continue;
                }
                if (parentDir == null) {
                    parentDir = Paths.get(".");
                }
                docsMap = generatePackageDocsFromBallerina(parentDir.toString(), fileName, packageFilter, isNative);
            } else {
                Path dirPath = Paths.get(source);
                // TODO fix this properly
                // TODO Temporary fix that creates .ballerina to create project structure
                Path projectFolder = dirPath.resolve(ProjectDirConstants.DOT_BALLERINA_DIR_NAME);
                Files.createDirectory(projectFolder);
                Path sourceRootPath = LauncherUtils.getSourceRootPath(dirPath.toString());
                docsMap = generatePackageDocsFromBallerina(sourceRootPath.toString(), dirPath, packageFilter, isNative);
            }
            if (docsMap.size() == 0) {
                out.println("docerina: no package definitions found!");
                return;
            }
            if (BallerinaDocUtils.isDebugEnabled()) {
                out.println("Generating HTML API documentation...");
            }
            String userDir = System.getProperty("user.dir");
            // If output directory is empty
            if (output == null) {
                output = System.getProperty(BallerinaDocConstants.HTML_OUTPUT_PATH_KEY, userDir + File.separator + "api-docs" + File.separator + "html");
            }
            // Create output directories
            Files.createDirectories(Paths.get(output));
            // Sort packages by package path
            List<BLangPackage> packageList = new ArrayList<>(docsMap.values());
            packageList.sort(Comparator.comparing(pkg -> pkg.packageID.toString()));
            // Iterate over the packages to generate the pages
            List<String> packageNames = new ArrayList<>(docsMap.keySet());
            // Sort the package names
            Collections.sort(packageNames);
            List<Link> packageNameList = PackageName.convertList(packageNames);
            if (packageNames.contains("ballerina.builtin")) {
                StaticCaption primitivesLinkName = new StaticCaption(BallerinaDocConstants.PRIMITIVE_TYPES_PAGE_NAME);
                packageNameList.add(0, new Link(primitivesLinkName, BallerinaDocConstants.PRIMITIVE_TYPES_PAGE_HREF, false));
            }
            // Generate pages for the packages
            String packageTemplateName = System.getProperty(BallerinaDocConstants.PACKAGE_TEMPLATE_NAME_KEY, "page");
            for (BLangPackage bLangPackage : packageList) {
                // Sort functions, connectors, structs, type mappers and annotationDefs
                bLangPackage.getFunctions().sort(Comparator.comparing(f -> (f.getReceiver() == null ? "" : f.getReceiver().getName()) + f.getName().getValue()));
                bLangPackage.getConnectors().sort(Comparator.comparing(c -> c.getName().getValue()));
                bLangPackage.getStructs().sort(Comparator.comparing(s -> s.getName().getValue()));
                bLangPackage.getAnnotations().sort(Comparator.comparing(a -> a.getName().getValue()));
                bLangPackage.getEnums().sort(Comparator.comparing(a -> a.getName().getValue()));
                // Sort connector actions
                if ((bLangPackage.getConnectors() != null) && (bLangPackage.getConnectors().size() > 0)) {
                    bLangPackage.getConnectors().forEach(connector -> connector.getActions().sort(Comparator.comparing(a -> a.getName().getValue())));
                }
                String packagePath = refinePackagePath(bLangPackage);
                Page page = Generator.generatePage(bLangPackage, packageNameList);
                String filePath = output + File.separator + packagePath + HTML;
                Writer.writeHtmlDocument(page, packageTemplateName, filePath);
                if ("ballerina.builtin".equals(packagePath)) {
                    Page primitivesPage = Generator.generatePageForPrimitives(bLangPackage, packageNameList);
                    String primitivesFilePath = output + File.separator + "primitive-types" + HTML;
                    Writer.writeHtmlDocument(primitivesPage, packageTemplateName, primitivesFilePath);
                }
            }
            // Generate the index file with the list of all packages
            String indexTemplateName = System.getProperty(BallerinaDocConstants.PACKAGE_TEMPLATE_NAME_KEY, "index");
            String indexFilePath = output + File.separator + "index" + HTML;
            Writer.writeHtmlDocument(packageNameList, indexTemplateName, indexFilePath);
            if (BallerinaDocUtils.isDebugEnabled()) {
                out.println("Copying HTML theme...");
            }
            BallerinaDocUtils.copyResources("docerina-theme", output);
        } catch (IOException e) {
            out.println(String.format("docerina: API documentation generation failed for %s: %s", source, e.getMessage()));
            log.error(String.format("API documentation generation failed for %s", source), e);
        }
    }
    try {
        String zipPath = System.getProperty(BallerinaDocConstants.OUTPUT_ZIP_PATH);
        if (zipPath != null) {
            BallerinaDocUtils.packageToZipFile(output, zipPath);
        }
    } catch (IOException e) {
        out.println(String.format("docerina: API documentation zip packaging failed for %s: %s", output, e.getMessage()));
        log.error(String.format("API documentation zip packaging failed for %s", output), e);
    }
}
Also used : Path(java.nio.file.Path) ProjectDirConstants(org.wso2.ballerinalang.compiler.util.ProjectDirConstants) Arrays(java.util.Arrays) Link(org.ballerinalang.docgen.model.Link) Generator(org.ballerinalang.docgen.Generator) LoggerFactory(org.slf4j.LoggerFactory) Compiler(org.wso2.ballerinalang.compiler.Compiler) PackageLoader(org.wso2.ballerinalang.compiler.PackageLoader) ArrayList(java.util.ArrayList) Page(org.ballerinalang.docgen.model.Page) Writer(org.ballerinalang.docgen.Writer) Map(java.util.Map) Names(org.wso2.ballerinalang.compiler.util.Names) Path(java.nio.file.Path) LauncherUtils(org.ballerinalang.launcher.LauncherUtils) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) PrintStream(java.io.PrintStream) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) Files(java.nio.file.Files) CompilerPhase(org.ballerinalang.compiler.CompilerPhase) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) CodeAnalyzer(org.wso2.ballerinalang.compiler.semantics.analyzer.CodeAnalyzer) File(java.io.File) SemanticAnalyzer(org.wso2.ballerinalang.compiler.semantics.analyzer.SemanticAnalyzer) FileVisitResult(java.nio.file.FileVisitResult) BallerinaDocUtils(org.ballerinalang.docgen.docs.utils.BallerinaDocUtils) StaticCaption(org.ballerinalang.docgen.model.StaticCaption) List(java.util.List) Paths(java.nio.file.Paths) StringJoiner(java.util.StringJoiner) PackageName(org.ballerinalang.docgen.model.PackageName) CompilerOptionName(org.ballerinalang.compiler.CompilerOptionName) Comparator(java.util.Comparator) CompilerOptions(org.wso2.ballerinalang.compiler.util.CompilerOptions) Collections(java.util.Collections) SymbolTable(org.wso2.ballerinalang.compiler.semantics.model.SymbolTable) CompilerContext(org.wso2.ballerinalang.compiler.util.CompilerContext) ArrayList(java.util.ArrayList) Page(org.ballerinalang.docgen.model.Page) IOException(java.io.IOException) StaticCaption(org.ballerinalang.docgen.model.StaticCaption) BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) Link(org.ballerinalang.docgen.model.Link)

Example 42 with Names

use of org.wso2.ballerinalang.compiler.util.Names in project ballerina by ballerina-lang.

the class BallerinaDocGenerator method generatePackageDocsFromBallerina.

/**
 * Generates {@link BLangPackage} objects for each Ballerina package from the given ballerina files.
 *
 * @param sourceRoot    points to the folder relative to which package path is given
 * @param packagePath   a {@link Path} object pointing either to a ballerina file or a folder with ballerina files.
 * @param packageFilter comma separated list of package names/patterns to be filtered from the documentation.
 * @param isNative      whether the given packages are native or not.
 * @return a map of {@link BLangPackage} objects. Key - Ballerina package name Value - {@link BLangPackage}
 */
protected static Map<String, BLangPackage> generatePackageDocsFromBallerina(String sourceRoot, Path packagePath, String packageFilter, boolean isNative) throws IOException {
    final List<Path> packagePaths = new ArrayList<>();
    if (Files.isDirectory(packagePath)) {
        BallerinaSubPackageVisitor subPackageVisitor = new BallerinaSubPackageVisitor(packagePath, packagePaths);
        Files.walkFileTree(packagePath, subPackageVisitor);
    } else {
        packagePaths.add(packagePath);
    }
    BallerinaDocDataHolder dataHolder = BallerinaDocDataHolder.getInstance();
    if (!isNative) {
        // This is necessary to be true in order to Ballerina to work properly
        System.setProperty("skipNatives", "true");
    }
    BLangPackage bLangPackage;
    for (Path path : packagePaths) {
        CompilerContext context = new CompilerContext();
        CompilerOptions options = CompilerOptions.getInstance(context);
        options.put(CompilerOptionName.PROJECT_DIR, sourceRoot);
        options.put(CompilerOptionName.COMPILER_PHASE, CompilerPhase.DESUGAR.toString());
        options.put(CompilerOptionName.PRESERVE_WHITESPACE, "false");
        Compiler compiler = Compiler.getInstance(context);
        // TODO: Remove this and the related constants once these are properly handled in the core
        if (BAL_BUILTIN.equals(path) || BAL_BUILTIN_CORE.equals(path)) {
            bLangPackage = loadBuiltInPackage(context);
        } else {
            // compile the given file
            bLangPackage = compiler.compile(getPackageNameFromPath(path));
        }
        if (bLangPackage == null) {
            out.println(String.format("docerina: invalid Ballerina package: %s", packagePath));
        } else {
            String packageName = bLangPackage.symbol.pkgID.name.value;
            if (isFilteredPackage(packageName, packageFilter)) {
                if (BallerinaDocUtils.isDebugEnabled()) {
                    out.println("Package " + packageName + " excluded");
                }
                continue;
            }
            dataHolder.getPackageMap().put(packageName, bLangPackage);
        }
    }
    return dataHolder.getPackageMap();
}
Also used : Path(java.nio.file.Path) Compiler(org.wso2.ballerinalang.compiler.Compiler) BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) CompilerContext(org.wso2.ballerinalang.compiler.util.CompilerContext) ArrayList(java.util.ArrayList) CompilerOptions(org.wso2.ballerinalang.compiler.util.CompilerOptions)

Example 43 with Names

use of org.wso2.ballerinalang.compiler.util.Names in project ballerina by ballerina-lang.

the class IdentifierLiteralServiceTest method testUsingIdentifierLiteralsInServiceAndResourceNames.

@Test(description = "Test using identifier literals in service and resource names", enabled = false)
public void testUsingIdentifierLiteralsInServiceAndResourceNames() {
    HTTPTestRequest cMsg = MessageUtils.generateHTTPMessage("/identifierLiteral/resource", "GET");
    HTTPCarbonMessage response = Services.invokeNew(application, cMsg);
    Assert.assertNotNull(response);
    BJSON bJson = new BJSON(new HttpMessageDataStreamer(response).getInputStream());
    Assert.assertEquals(bJson.value().get("key").asText(), "keyVal");
    Assert.assertEquals(bJson.value().get("value").asText(), "valueOfTheString");
}
Also used : HTTPCarbonMessage(org.wso2.transport.http.netty.message.HTTPCarbonMessage) HttpMessageDataStreamer(org.wso2.transport.http.netty.message.HttpMessageDataStreamer) HTTPTestRequest(org.ballerinalang.test.services.testutils.HTTPTestRequest) BJSON(org.ballerinalang.model.values.BJSON) Test(org.testng.annotations.Test)

Example 44 with Names

use of org.wso2.ballerinalang.compiler.util.Names in project ballerina by ballerina-lang.

the class HTTPSessionEssentialMethodsTest method testCheckPathValidityPerService.

@Test(description = "Test for path limitation per service")
public void testCheckPathValidityPerService() {
    HTTPTestRequest cMsg = MessageUtils.generateHTTPMessage("/sample2/names", "GET");
    HTTPCarbonMessage response = Services.invokeNew(compileResult, TEST_ENDPOINT_NAME, cMsg);
    Assert.assertNotNull(response);
    String responseMsgPayload = StringUtils.getStringFromInputStream(new HttpMessageDataStreamer(response).getInputStream());
    ;
    Assert.assertNotNull(responseMsgPayload);
    Assert.assertEquals(responseMsgPayload, "arraysize:2");
    String cookie = response.getHeader(RESPONSE_COOKIE_HEADER);
    String sessionId = CookieUtils.getCookie(cookie).value;
    cMsg = MessageUtils.generateHTTPMessage("/sample2/names3", "GET");
    cMsg.setHeader(COOKIE_HEADER, SESSION_ID + sessionId);
    response = Services.invokeNew(compileResult, TEST_ENDPOINT_NAME, cMsg);
    Assert.assertNotNull(response);
    responseMsgPayload = StringUtils.getStringFromInputStream(new HttpMessageDataStreamer(response).getInputStream());
    Assert.assertNotNull(responseMsgPayload);
    Assert.assertEquals(responseMsgPayload, "4");
}
Also used : HTTPCarbonMessage(org.wso2.transport.http.netty.message.HTTPCarbonMessage) HttpMessageDataStreamer(org.wso2.transport.http.netty.message.HttpMessageDataStreamer) HTTPTestRequest(org.ballerinalang.test.services.testutils.HTTPTestRequest) Test(org.testng.annotations.Test)

Aggregations

ArrayList (java.util.ArrayList)10 Query (javax.persistence.Query)8 TaskStatus (org.wso2.carbon.humantask.core.dao.TaskStatus)8 Test (org.testng.annotations.Test)6 BLangVariable (org.wso2.ballerinalang.compiler.tree.BLangVariable)5 Name (org.wso2.ballerinalang.compiler.util.Name)5 Map (java.util.Map)4 BLangXMLQName (org.wso2.ballerinalang.compiler.tree.expressions.BLangXMLQName)4 CompilerContext (org.wso2.ballerinalang.compiler.util.CompilerContext)4 HTTPTestRequest (org.ballerinalang.test.services.testutils.HTTPTestRequest)3 BLangPackage (org.wso2.ballerinalang.compiler.tree.BLangPackage)3 BLangRecordLiteral (org.wso2.ballerinalang.compiler.tree.expressions.BLangRecordLiteral)3 BLangAssignment (org.wso2.ballerinalang.compiler.tree.statements.BLangAssignment)3 Response (feign.Response)2 IOException (java.io.IOException)2 Path (java.nio.file.Path)2 Arrays (java.util.Arrays)2 Date (java.util.Date)2 HashMap (java.util.HashMap)2 Iterator (java.util.Iterator)2