use of com.codename1.io.File in project CodenameOne by codenameone.
the class CN1BuildMojo method doAndroidLocalBuild.
private void doAndroidLocalBuild(File tmpProjectDir, Properties props, File distJar) throws MojoExecutionException {
if (BUILD_TARGET_ANDROID_PROJECT.equals(buildTarget)) {
File generatedProject = getGeneratedAndroidProjectSourceDirectory();
getLog().info("Generating android gradle Project to " + generatedProject + "...");
try {
if (generatedProject.exists()) {
getLog().info("Android gradle project already exists. Checking to see if it needs updating...");
if (getSourcesModificationTime() <= lastModifiedRecursive(generatedProject)) {
getLog().info("Sources have not changed. Skipping android gradle project generation");
if (open) {
openAndroidStudioProject(generatedProject);
}
return;
}
}
} catch (IOException ex) {
throw new MojoExecutionException("Failed to find last modification time of " + generatedProject);
}
}
File codenameOneJar = getJar("com.codenameone", "codenameone-core");
AndroidGradleBuilder e = new AndroidGradleBuilder();
e.setBuildTarget(buildTarget);
e.setLogger(getLog());
File buildDirectory = new File(tmpProjectDir, "dist" + File.separator + "android-build");
e.setBuildDirectory(buildDirectory);
e.setCodenameOneJar(codenameOneJar);
e.setPlatform("android");
BuildRequest r = new BuildRequest();
r.setDisplayName(props.getProperty("codename1.displayName"));
r.setPackageName(props.getProperty("codename1.packageName"));
r.setMainClass(props.getProperty("codename1.mainName"));
r.setVersion(props.getProperty("codename1.version"));
String iconPath = props.getProperty("codename1.icon");
File iconFile = new File(iconPath);
if (!iconFile.isAbsolute()) {
iconFile = new File(getCN1ProjectDir(), iconPath);
}
try {
BufferedImage bi = ImageIO.read(iconFile);
if (bi.getWidth() != 512 || bi.getHeight() != 512) {
throw new MojoExecutionException("The icon must be a 512x512 pixel PNG image. It will be scaled to the proper sizes for devices");
}
r.setIcon(iconFile.getAbsolutePath());
} catch (IOException ex) {
throw new MojoExecutionException("Error reading the icon: the icon must be a 512x512 pixel PNG image. It will be scaled to the proper sizes for devices");
}
r.setVendor(props.getProperty("codename1.vendor"));
r.setSubTitle(props.getProperty("codename1.secondaryTitle"));
r.setType("android");
r.setKeystoreAlias(props.getProperty("codename1.android.keystoreAlias"));
String keystorePath = props.getProperty("codename1.android.keystore");
if (keystorePath != null) {
File keystoreFile = new File(keystorePath);
if (!keystoreFile.isAbsolute()) {
keystoreFile = new File(getCN1ProjectDir(), keystorePath);
}
if (keystoreFile.exists() && keystoreFile.isFile()) {
try {
r.setCertificate(keystoreFile.getAbsolutePath());
} catch (IOException ex) {
throw new MojoExecutionException("Failed to load keystore file. ", ex);
}
} else {
File androidCerts = new File(getCN1ProjectDir(), "androidCerts");
androidCerts.mkdirs();
keystoreFile = new File(androidCerts, "KeyChain.ks");
if (!keystoreFile.exists()) {
try {
String alias = r.getKeystoreAlias();
if (alias == null || alias.isEmpty()) {
alias = "androidKey";
r.setKeystoreAlias(alias);
props.setProperty("codename1.android.keystoreAlias", alias);
}
String password = props.getProperty("codename1.android.keystorePassword");
if (password == null || password.isEmpty()) {
password = "password";
props.setProperty("codename1.android.keystorePassword", password);
}
getLog().info("No Keystore found. Generating one now");
String keyPath = generateCertificate(password, alias, r.getVendor(), "", r.getVendor(), "Vancouver", "BC", "CA", false);
FileUtils.copyFile(new File(keyPath), keystoreFile);
r.setCertificate(keystoreFile.getAbsolutePath());
getLog().info("Generated keystore with password 'password' at " + keystoreFile + ". alias=androidKey");
new File(keyPath).delete();
SortedProperties sp = new SortedProperties();
try (FileInputStream fis = new FileInputStream(new File(getCN1ProjectDir(), "codenameone_settings.properties"))) {
sp.load(fis);
}
sp.setProperty("codename1.android.keystore", keystoreFile.getAbsolutePath());
sp.setProperty("codename1.android.keystorePassword", password);
sp.setProperty("codename1.android.keystoreAlias", alias);
try (FileOutputStream fos = new FileOutputStream(new File(getCN1ProjectDir(), "codenameone_settings.properties"))) {
sp.store(fos, "Updated keystore");
}
} catch (Exception ex) {
getLog().error("Failed to generate keystore", ex);
throw new MojoExecutionException("Failed to generate keystore", ex);
}
}
}
}
r.setCertificatePassword(props.getProperty("codename1.android.keystorePassword"));
for (Object k : props.keySet()) {
String key = (String) k;
if (key.startsWith("codename1.arg.")) {
String value = props.getProperty(key);
String currentKey = key.substring(14);
if (currentKey.indexOf(' ') > -1) {
throw new MojoExecutionException("The build argument contains a space in the key: '" + currentKey + "'");
}
r.putArgument(currentKey, value);
}
}
BuildRequest request = r;
request.setIncludeSource(true);
String testBuild = request.getArg("build.unitTest", null);
if (testBuild != null && testBuild.equals("1")) {
e.setUnitTestMode(true);
}
try {
getLog().info("Starting android project builder...");
boolean result = e.build(distJar, request);
getLog().info("Android project builder completed with result " + result);
if (!result) {
getLog().error("Received false return value from build()");
throw new MojoExecutionException("Android build failed. Received false return value for build");
}
if (BUILD_TARGET_ANDROID_PROJECT.equals(buildTarget) && e.getGradleProjectDirectory() != null) {
File gradleProject = e.getGradleProjectDirectory();
File output = getGeneratedAndroidProjectSourceDirectory();
output.getParentFile().mkdirs();
try {
getLog().info("Copying Gradle Project to " + output);
FileUtils.copyDirectory(gradleProject, output);
} catch (IOException ex) {
throw new MojoExecutionException("Failed to copy gradle project at " + gradleProject + " to " + output, ex);
}
}
if (open) {
openAndroidStudioProject(getGeneratedAndroidProjectSourceDirectory());
}
} catch (BuildException ex) {
getLog().error("Failed to build Android project with error: " + ex.getMessage(), ex);
getLog().error(e.getErrorMessage());
throw new MojoExecutionException("Failed to build android app", ex);
} finally {
e.cleanup();
}
}
use of com.codename1.io.File in project CodenameOne by codenameone.
the class GenerateAppProjectMojo method copySourceFiles.
private void copySourceFiles() {
{
Copy copy = (Copy) antProject().createTask("copy");
copy.setTodir(targetSrcDir("java"));
copy.setOverwrite(true);
FileSet files = new FileSet();
files.setProject(antProject());
files.setDir(sourceSrcDir());
files.setIncludes("**/*.java, *.java");
copy.addFileset(files);
copy.execute();
}
{
Copy copy = (Copy) antProject().createTask("copy");
copy.setTodir(targetSrcDir("resources"));
copy.setOverwrite(true);
FileSet files = new FileSet();
files.setProject(antProject());
files.setDir(sourceSrcDir());
files.setExcludes("**/*.kt, **/*.java, **/*.mirah, *.kt, *.java, *.mirah");
copy.addFileset(files);
copy.execute();
File cn1PropertiesFile = new File(sourceProject, "codenameone_settings.properties");
if (cn1PropertiesFile.exists()) {
Properties cn1Properties = new SortedProperties();
try (FileInputStream input = new FileInputStream(cn1PropertiesFile)) {
cn1Properties.load(input);
} catch (IOException ex) {
getLog().error("Failed to open " + cn1Properties + " while checking or cssTheme property", ex);
}
if ("true".equals(cn1Properties.getProperty("codename1.cssTheme", "false"))) {
// If we're using a CSS theme, then we need to delete the theme.res file
File themeRes = new File(targetSrcDir("resources"), "theme.res");
if (themeRes.exists()) {
getLog().debug("Deleting " + themeRes + " because this project uses CSS themes. In maven the theme.res is generated at build time, and is never saved in the source directory.");
themeRes.delete();
}
}
}
}
if (hasFilesWithSuffix(sourceSrcDir(), ".kt")) {
targetSrcDir("kotlin").mkdirs();
Copy copy = (Copy) antProject().createTask("copy");
copy.setTodir(targetSrcDir("kotlin"));
copy.setOverwrite(true);
FileSet files = new FileSet();
files.setProject(antProject());
files.setDir(sourceSrcDir());
files.setIncludes("**/*.kt, *.kt");
copy.addFileset(files);
copy.execute();
}
if (hasFilesWithSuffix(sourceSrcDir(), ".mirah")) {
targetSrcDir("mirah").mkdirs();
Copy copy = (Copy) antProject().createTask("copy");
copy.setTodir(targetSrcDir("mirah"));
copy.setOverwrite(true);
FileSet files = new FileSet();
files.setProject(antProject());
files.setDir(sourceSrcDir());
files.setIncludes("**/*.mirah, *.mirah");
copy.addFileset(files);
copy.execute();
}
}
use of com.codename1.io.File in project CodenameOne by codenameone.
the class GenerateAppProjectMojo method generateProject.
private void generateProject() throws MojoExecutionException {
String archetypeVersion = "LATEST";
try {
MavenXpp3Reader reader = new MavenXpp3Reader();
Model model = reader.read(getClass().getResourceAsStream("/META-INF/maven/com.codenameone/codenameone-maven-plugin/pom.xml"));
archetypeVersion = model.getVersion();
} catch (Exception ex) {
getLog().warn("Attempted to read archetype version from embedded pom.xml file but failed", ex);
}
InvocationRequest request = new DefaultInvocationRequest();
// request.setPomFile( new File( "/path/to/pom.xml" ) );
request.setGoals(Collections.singletonList("archetype:generate"));
String[] propsArr = { "interactiveMode=false", "archetypeArtifactId=cn1app-archetype", "archetypeGroupId=com.codenameone", "archetypeVersion=" + archetypeVersion, "artifactId=" + artifactId, "groupId=" + groupId, "version=" + version, "mainName=" + mainName(), "package=" + packageName() };
Properties props = new Properties();
for (String prop : propsArr) {
int eqpos = prop.indexOf("=");
if (eqpos > 0) {
props.setProperty(prop.substring(0, eqpos), prop.substring(eqpos + 1));
} else if (eqpos < 0) {
props.setProperty(prop, "true");
}
}
if (getLog().isDebugEnabled()) {
request.setDebug(true);
}
request.setShowErrors(true);
request.setProperties(props);
Invoker invoker = new DefaultInvoker();
try {
InvocationResult result = invoker.execute(request);
if (result.getExitCode() != 0) {
throw new MojoExecutionException("Failed to generate project using cn1app-archetype. Exit code " + result.getExitCode());
}
} catch (MavenInvocationException ex) {
throw new MojoExecutionException(ex.getMessage(), ex);
}
}
use of com.codename1.io.File in project CodenameOne by codenameone.
the class GenerateAppProjectMojo method injectDependencies.
private void injectDependencies() throws MojoExecutionException {
if (!generateAppProjectConfigFile().exists()) {
return;
}
try {
Properties props = new Properties();
new RichPropertiesReader().load(generateAppProjectConfigFile(), props);
String dependencies = props.getProperty("dependencies");
String parentDependencies = props.getProperty("parentDependencies");
if (targetCommonPomXml().exists()) {
Model model;
ModelETL modelETL;
/*
try (FileInputStream fis = new FileInputStream(targetCommonPomXml())){
MavenXpp3Reader reader = new MavenXpp3Reader();
model = reader.read(fis);
} catch (Exception ex) {
throw new MojoExecutionException("Failed to read pom.xml file from "+targetCommonPomXml(), ex);
}
*/
try {
ModelETLRequest modelETLRequest = new ModelETLRequest();
modelETL = new JDomModelETLFactory().newInstance(modelETLRequest);
modelETL.extract(targetCommonPomXml());
model = modelETL.getModel();
} catch (Exception ex) {
throw new MojoExecutionException("Failed to read pom.xml file from " + targetCommonPomXml(), ex);
}
if (dependencies != null) {
String dummyModelStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n" + " <modelVersion>4.0.0</modelVersion>\n" + " <groupId>link.sharpe</groupId>\n" + " <artifactId>mavenproject1</artifactId>\n" + " <version>1.0-SNAPSHOT</version>\n" + " <dependencies>\n" + dependencies + " </dependencies>\n" + "</project>";
Model dummyModel;
try {
MavenXpp3Reader reader = new MavenXpp3Reader();
dummyModel = reader.read(new CharArrayReader(dummyModelStr.toCharArray()));
} catch (Exception ex) {
throw new MojoExecutionException("Failed to read dummy pom.xml file while injecting dependencies into " + targetCommonPomXml(), ex);
}
for (Dependency dep : dummyModel.getDependencies()) {
model.addDependency(dep);
}
/*
MavenXpp3Writer writer = new MavenXpp3Writer();
try (FileOutputStream fos = new FileOutputStream(targetCommonPomXml())) {
writer.write(fos, model);
}
*/
modelETL.load(targetCommonPomXml());
}
}
if (targetRootPomXml().exists()) {
Model model;
ModelETL modelETL;
/*
try (FileInputStream fis = new FileInputStream(targetRootPomXml())){
MavenXpp3Reader reader = new MavenXpp3Reader();
model = reader.read(fis);
} catch (Exception ex) {
throw new MojoExecutionException("Failed to read pom.xml file from "+targetRootPomXml(), ex);
}
*/
try {
ModelETLRequest modelETLRequest = new ModelETLRequest();
modelETL = new JDomModelETLFactory().newInstance(modelETLRequest);
modelETL.extract(targetRootPomXml());
model = modelETL.getModel();
} catch (Exception ex) {
throw new MojoExecutionException("Failed to read pom.xml file from " + targetRootPomXml(), ex);
}
if (parentDependencies != null) {
// getLog().info("Parent dependencies: "+parentDependencies);
String dummyModelStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n" + " <modelVersion>4.0.0</modelVersion>\n" + " <groupId>link.sharpe</groupId>\n" + " <artifactId>mavenproject1</artifactId>\n" + " <version>1.0-SNAPSHOT</version>\n" + " <dependencies>\n" + parentDependencies + " </dependencies>\n" + "</project>";
Model dummyModel;
try {
MavenXpp3Reader reader = new MavenXpp3Reader();
dummyModel = reader.read(new CharArrayReader(dummyModelStr.toCharArray()));
} catch (Exception ex) {
throw new MojoExecutionException("Failed to read dummy pom.xml file while injecting dependencies into " + targetRootPomXml(), ex);
}
for (Dependency dep : dummyModel.getDependencies()) {
model.addDependency(dep);
}
/*
MavenXpp3Writer writer = new MavenXpp3Writer();
try (FileOutputStream fos = new FileOutputStream(targetRootPomXml())) {
writer.write(fos, model);
}
*/
modelETL.load(targetRootPomXml());
}
}
} catch (IOException ex) {
throw new MojoExecutionException("Failed to process configuration for generateAppProjectConfigFile " + generateAppProjectConfigFile(), ex);
} catch (RichPropertiesReader.ConfigSyntaxException ex) {
throw new MojoExecutionException("Failed to process configuration for generateAppProjectConfigFile " + generateAppProjectConfigFile(), ex);
}
}
use of com.codename1.io.File in project CodenameOne by codenameone.
the class GenerateArchetypeFromTemplateMojo method processString.
/**
* Processes a string with template instructions. This string may have [dependencies], [css], or [properties]
* sections with content that will be injected.
*
* WARNING: This will make changes to the existing pom.xml file, and the src/main/css/theme.css file.
*
* @param contents String contents to be processed.
* @throws MojoExecutionException
*/
private void processString(String contents, File projectDir) throws MojoExecutionException {
File archetypeResourcesDir = new File(projectDir, path("src", "main", "resources", "archetype-resources"));
try {
File commonProjectDir = new File(archetypeResourcesDir, "common");
File pomFile = new File(commonProjectDir, "pom.xml");
File codenameoneSettingsProperties = new File(commonProjectDir, "codenameone_settings.properties");
File themeCss = new File(commonProjectDir, "src" + File.separator + "main" + File.separator + "css");
String pomContents = FileUtils.readFileToString(pomFile, "UTF-8");
final String origPomContents = pomContents;
String dependencies = extractDependencies(contents);
if (!dependencies.isEmpty()) {
getLog().info("Injecting dependencies:\n" + dependencies + " \ninto " + pomFile);
String marker = "<!-- INJECT DEPENDENCIES -->";
pomContents = pomContents.replace(marker, dependencies + "\n" + marker);
}
String properties = extractProperties(contents);
if (!properties.isEmpty()) {
SortedProperties props = new SortedProperties();
props.load(new StringReader(properties));
if (codenameoneSettingsProperties == null || !codenameoneSettingsProperties.exists()) {
throw new MojoExecutionException("Cannot find codenameone_settings.properties");
}
SortedProperties cn1Props = new SortedProperties();
cn1Props.load(new FileReader(codenameoneSettingsProperties));
cn1Props.putAll(props);
getLog().info("Injecting properties:\n" + props + "\n into " + codenameoneSettingsProperties);
cn1Props.store(new FileWriter(codenameoneSettingsProperties), "Injected properties from template");
}
String css = extractCSS(contents);
if (!css.isEmpty()) {
if (!themeCss.exists()) {
themeCss.getParentFile().mkdirs();
}
getLog().info("Adding CSS to " + themeCss);
FileUtils.writeStringToFile(themeCss, css, "UTF-8");
}
// We change the codename1.template property to codename1.template.installed so that
// this mojo won't operate on this project again. (Notice the check at the beginning
// of execImpl() to return if it doesn't find the codename1.template property).
pomContents = pomContents.replace("<codename1.template>", "<codename1.templated.installed>").replace("</codename1.template>", "</codename1.template.installed>");
if (!pomContents.equals(origPomContents)) {
getLog().info("Writing changes to " + pomFile);
FileUtils.writeStringToFile(pomFile, pomContents, "UTF-8");
}
for (FileContent file : extractFiles(contents)) {
File f = new File(commonProjectDir, file.path);
f.getParentFile().mkdirs();
FileUtils.writeStringToFile(f, file.content, "UTF-8");
}
} catch (TemplateParseException ex) {
throw new MojoExecutionException("Syntax error in template file", ex);
} catch (IOException ex) {
throw new MojoExecutionException("Failed to process template file", ex);
}
}
Aggregations