Search in sources :

Example 1 with PatternFileSelector

use of org.apache.commons.vfs2.PatternFileSelector in project CodenameOne by codenameone.

the class CN1BuildMojo method createAntProject.

private void createAntProject() throws IOException, LibraryPropertiesException, MojoExecutionException {
    File cn1dir = new File(project.getBuild().getDirectory() + File.separator + "codenameone");
    File antProject = new File(cn1dir, "antProject");
    antProject.mkdirs();
    File codenameOneSettings = new File(getCN1ProjectDir(), "codenameone_settings.properties");
    File icon = new File(getCN1ProjectDir(), "icon.png");
    if (icon.exists()) {
        FileUtils.copyFile(icon, new File(antProject, "icon.png"));
    } else {
        FileUtils.copyInputStreamToFile(getClass().getResourceAsStream("codenameone-icon.png"), new File(antProject, "icon.png"));
    }
    File codenameOneSettingsCopy = new File(antProject, codenameOneSettings.getName());
    FileUtils.copyFile(codenameOneSettings, codenameOneSettingsCopy);
    FileUtils.copyInputStreamToFile(getClass().getResourceAsStream("buildxml-template.xml"), new File(antProject, "build.xml"));
    File distDir = new File(antProject, "dist");
    distDir.mkdirs();
    // Build a jar with all dependencies that we will send to the build server.
    File jarWithDependencies = new File(path(project.getBuild().getDirectory(), project.getBuild().getFinalName() + "-" + buildTarget + "-jar-with-dependencies.jar"));
    List<String> cpElements;
    try {
        // getLog().info("Classpath Elements: "+ project.getCompileClasspathElements());
        cpElements = project.getCompileClasspathElements();
    } catch (Exception ex) {
        throw new MojoExecutionException("Failed to get classpath elements", ex);
    }
    File appExtensionsJar = getAppExtensionsJar();
    if (appExtensionsJar != null) {
        cpElements.add(appExtensionsJar.getAbsolutePath());
    }
    File stringsJar = getStringsJar();
    if (stringsJar != null) {
        cpElements.add(stringsJar.getAbsolutePath());
    }
    getLog().debug("Classpath Elements: " + cpElements);
    if (jarWithDependencies.exists()) {
        getLog().debug("Found jar file with dependencies at " + jarWithDependencies + ". Will use that one unless it is out of date.");
        for (String artifact : cpElements) {
            File jar = new File(artifact);
            if (jar.isDirectory()) {
                if (jarWithDependencies.lastModified() < lastModifiedRecursive(jar)) {
                    getLog().debug("Jar file out of date.  Dependencies have changed. " + jarWithDependencies + ". Deleting");
                    jarWithDependencies.delete();
                    break;
                }
            } else if (jar.exists() && jar.lastModified() > jarWithDependencies.lastModified()) {
                // One of the dependency jar files is newer... so we delete the dependencies jar file
                // and will generate a new one.
                getLog().debug("Jar file out of date.  Dependencies have changed. " + jarWithDependencies + ". Deleting");
                jarWithDependencies.delete();
                break;
            }
        }
    }
    if (!jarWithDependencies.exists()) {
        getLog().info(jarWithDependencies + " not found.  Generating jar with dependencies now");
        // Jars that should be stripped out and not sent to the server
        List<String> blackListJars = new ArrayList<String>();
        getLog().info("Project artifacts: " + project.getArtifacts());
        for (Artifact artifact : project.getArtifacts()) {
            boolean addToBlacklist = false;
            if (artifact.getGroupId().equals("com.codenameone") && contains(artifact.getArtifactId(), BUNDLE_ARTIFACT_ID_BLACKLIST)) {
                addToBlacklist = true;
            }
            if (!addToBlacklist && !isLocalBuildTarget(buildTarget)) {
                // for local builds, it's easier to just include it.
                if (artifact.getGroupId().equals("org.jetbrains.kotlin") && artifact.getArtifactId().equals("kotlin-stdlib")) {
                    addToBlacklist = true;
                    serverMustProvideKotlinVersion = artifact.getVersion();
                    getLog().debug("Adding kotlin-stdlib to blacklist.  Server will provide this:" + artifact);
                }
            }
            if (!addToBlacklist && !"compile".equals(artifact.getScope())) {
                addToBlacklist = true;
            }
            if (addToBlacklist) {
                File jar = getJar(artifact);
                if (jar != null) {
                    blackListJars.add(jar.getAbsolutePath());
                    blackListJars.add(jar.getPath());
                    try {
                        blackListJars.add(jar.getCanonicalPath());
                        getLog().debug("Added " + jar + " to blacklist");
                    } catch (Exception ex) {
                    }
                }
            }
        }
        getLog().debug("Merging compile classpath elements into jar with dependencies: " + cpElements);
        List<File> jarsToMerge = new ArrayList<File>();
        for (String element : cpElements) {
            String canonicalEl = element;
            try {
                canonicalEl = new File(canonicalEl).getCanonicalPath();
            } catch (Exception ex) {
            }
            if (blackListJars.contains(element) || blackListJars.contains(canonicalEl)) {
                getLog().debug("NOT adding jar " + element + " because it is on the blacklist");
                continue;
            }
            if (!new File(element).exists()) {
                continue;
            }
            getLog().debug("Adding jar " + element + " to " + jarWithDependencies + " Jar file=" + element);
            jarsToMerge.add(new File(element));
        }
        mergeJars(jarWithDependencies, jarsToMerge.toArray(new File[jarsToMerge.size()]));
    }
    try {
        updateCodenameOne(false);
    } catch (MojoExecutionException ex) {
        getLog().error("Failed to update Codename One");
        throw new IOException("Failed to update Codename One", ex);
    }
    File antDistDir = new File(antProject, "dist");
    File antDistJar = new File(antDistDir, project.getBuild().getFinalName() + "-" + buildTarget + "-jar-with-dependencies.jar");
    antDistDir.mkdirs();
    FileUtils.copyFile(jarWithDependencies, antDistJar);
    Properties p = new Properties();
    p.setProperty("codenameone_settings.properties", codenameOneSettingsCopy.getAbsolutePath());
    p.setProperty("CodeNameOneBuildClient.jar", path(System.getProperty("user.home"), ".codenameone", "CodeNameOneBuildClient.jar"));
    p.setProperty("dist.jar", antDistJar.getAbsolutePath());
    if (automated) {
        p.setProperty("automated", "true");
    }
    getLog().info("Running ANT build target " + buildTarget);
    String logPasskey = UUID.randomUUID().toString();
    Properties cn1SettingsProps = new Properties();
    try (FileInputStream fis = new FileInputStream(codenameOneSettingsCopy)) {
        cn1SettingsProps.load(fis);
    }
    if (serverMustProvideKotlinVersion != null) {
        cn1SettingsProps.setProperty("codename1.arg.requireKotlinStdlib", serverMustProvideKotlinVersion);
    }
    FileSystemManager fsManager = VFS.getManager();
    FileObject jarFile = fsManager.resolveFile("jar:" + jarWithDependencies.getAbsolutePath() + "!/META-INF/codenameone");
    if (jarFile != null) {
        FileObject[] appendedPropsFiles = jarFile.findFiles(new PatternFileSelector(".*\\/codenameone_library_appended.properties"));
        if (appendedPropsFiles != null) {
            for (FileObject appendedPropsFile : appendedPropsFiles) {
                SortedProperties appendedProps = new SortedProperties();
                try (InputStream appendedPropsIn = appendedPropsFile.getContent().getInputStream()) {
                    appendedProps.load(appendedPropsIn);
                }
                for (String propName : appendedProps.stringPropertyNames()) {
                    String propVal = appendedProps.getProperty(propName);
                    if (!cn1SettingsProps.containsKey(propName)) {
                        cn1SettingsProps.put(propName, propVal);
                    } else {
                        String existing = cn1SettingsProps.getProperty(propName);
                        if (!existing.contains(propVal)) {
                            cn1SettingsProps.setProperty(propName, existing + propVal);
                        }
                    }
                }
            }
        }
        FileObject[] requiredPropsFiles = jarFile.findFiles(new PatternFileSelector(".*\\/codenameone_library_required.properties"));
        if (requiredPropsFiles != null) {
            for (FileObject requiredPropsFile : requiredPropsFiles) {
                SortedProperties requiredProps = new SortedProperties();
                try (InputStream appendedPropsIn = requiredPropsFile.getContent().getInputStream()) {
                    requiredProps.load(appendedPropsIn);
                }
                String artifactId = requiredPropsFile.getParent().getName().getBaseName();
                String groupId = requiredPropsFile.getParent().getParent().getName().getBaseName();
                String libraryName = groupId + ":" + artifactId;
                cn1SettingsProps = mergeRequiredProperties(libraryName, requiredProps, cn1SettingsProps);
            }
        }
    }
    cn1SettingsProps.setProperty("codename1.arg.hyp.beamId", logPasskey);
    cn1SettingsProps.setProperty("codename1.arg.maven.codenameone-core.version", cn1MavenVersion);
    cn1SettingsProps.setProperty("codename1.arg.maven.codenameone-maven-plugin", cn1MavenPluginVersion);
    try (FileOutputStream fos = new FileOutputStream(codenameOneSettingsCopy)) {
        cn1SettingsProps.store(fos, "");
    }
    final Process[] proc = new Process[1];
    final boolean[] closingHypLog = new boolean[1];
    Thread hyperBeamThread = new Thread(() -> {
        ProcessBuilder pb = new ProcessBuilder("hyp", "beam", logPasskey);
        pb.redirectErrorStream(true);
        try {
            proc[0] = pb.start();
            InputStream out = proc[0].getInputStream();
            byte[] buffer = new byte[4000];
            while (isAlive(proc[0])) {
                int no = out.available();
                if (no > 0) {
                    int n = out.read(buffer, 0, Math.min(no, buffer.length));
                    getLog().info(new String(buffer, 0, n));
                }
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                }
            }
        } catch (Exception ex) {
            if (!closingHypLog[0]) {
                getLog().warn("Failed to start hyperlog.  The build log will not stream to your console.  If the build fails, you can download the error log at https://cloud.codenameone.com/secure/index.html");
                getLog().debug(ex);
            }
        }
    });
    try {
        if (isLocalBuildTarget(buildTarget)) {
            automated = false;
            if (buildTarget.contains("android") || BUILD_TARGET_ANDROID_PROJECT.equals(buildTarget)) {
                doAndroidLocalBuild(antProject, cn1SettingsProps, antDistJar);
            } else if (buildTarget.contains("ios") || BUILD_TARGET_XCODE_PROJECT.equals(buildTarget)) {
                doIOSLocalBuild(antProject, cn1SettingsProps, antDistJar);
            } else {
                throw new MojoExecutionException("Build target not supported " + buildTarget);
            }
        } else {
            if (automated) {
                getLog().debug("Attempting to start hyper beam stream the build log to the console");
                hyperBeamThread.start();
            }
            AntExecutor.executeAntTask(new File(antProject, "build.xml").getAbsolutePath(), buildTarget, p);
        }
    } finally {
        if (automated) {
            try {
                closingHypLog[0] = true;
                proc[0].destroyForcibly();
            } catch (Exception ex) {
            }
        }
    }
    if (automated) {
        getLog().info("Extracting server result");
        File result = new File(antDistDir, "result.zip");
        if (!result.exists()) {
            throw new IOException("Failed to find result.zip after automated build");
        }
        Expand unzip = (Expand) this.antProject.createTask("unzip");
        unzip.setSrc(result);
        File resultDir = new File(antDistDir, "result");
        resultDir.mkdir();
        unzip.setDest(resultDir);
        unzip.execute();
        for (File child : resultDir.listFiles()) {
            String name = child.getName();
            int dotpos = name.lastIndexOf(".");
            if (dotpos < 0) {
                continue;
            }
            String extension = name.substring(dotpos);
            String base = name.substring(0, dotpos);
            File copyTo = new File(project.getBuild().getDirectory() + File.separator + project.getBuild().getFinalName() + extension);
            FileUtils.copyFile(child, copyTo);
            if (".war".equals(extension)) {
                projectHelper.attachArtifact(project, "war", copyTo);
            } else if (".zip".equals(extension) && "javascript".equals(buildTarget)) {
                projectHelper.attachArtifact(project, "zip", "webapp", copyTo);
            } else if (".dmg".equals(extension) && "mac-os-x-desktop".equals(buildTarget)) {
                projectHelper.attachArtifact(project, "dmg", "mac-app", copyTo);
            } else if (".pkg".equals(extension) && "mac-os-x-desktop".equals(buildTarget)) {
                projectHelper.attachArtifact(project, "pkg", "mac-app-installer", copyTo);
            }
        }
        FileUtils.deleteDirectory(resultDir);
        result.delete();
        afterBuild();
    }
}
Also used : SortedProperties(com.codename1.ant.SortedProperties) FileObject(org.apache.commons.vfs2.FileObject) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) SortedProperties(com.codename1.ant.SortedProperties) FileSystemManager(org.apache.commons.vfs2.FileSystemManager) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) Artifact(org.apache.maven.artifact.Artifact) Expand(org.apache.tools.ant.taskdefs.Expand) PatternFileSelector(org.apache.commons.vfs2.PatternFileSelector)

Aggregations

SortedProperties (com.codename1.ant.SortedProperties)1 FileObject (org.apache.commons.vfs2.FileObject)1 FileSystemManager (org.apache.commons.vfs2.FileSystemManager)1 PatternFileSelector (org.apache.commons.vfs2.PatternFileSelector)1 Artifact (org.apache.maven.artifact.Artifact)1 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)1 MojoFailureException (org.apache.maven.plugin.MojoFailureException)1 Expand (org.apache.tools.ant.taskdefs.Expand)1