Skip to content

Commit

Permalink
Added the ability to have constraints on entities. Sorry this breaks the
Browse files Browse the repository at this point in the history
model json grammar.
  • Loading branch information
BoD committed Mar 13, 2013
1 parent 150ea42 commit aaffd3f
Show file tree
Hide file tree
Showing 9 changed files with 148 additions and 61 deletions.
2 changes: 1 addition & 1 deletion .project
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>GenerateAndroidProvider</name>
<name>android-contentprovider-generator</name>
<comment></comment>
<projects>
</projects>
Expand Down
111 changes: 65 additions & 46 deletions src/main/java/org/jraf/androidcontentprovidergenerator/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.jraf.androidcontentprovidergenerator.model.Constraint;
import org.jraf.androidcontentprovidergenerator.model.Entity;
import org.jraf.androidcontentprovidergenerator.model.Field;
import org.jraf.androidcontentprovidergenerator.model.Model;
Expand All @@ -51,9 +52,9 @@
import freemarker.template.TemplateException;

public class Main {
private static final String TAG = Constants.TAG + Main.class.getSimpleName();
private static String TAG = Constants.TAG + Main.class.getSimpleName();

private static final String FILE_CONFIG = "_config.json";
private static String FILE_CONFIG = "_config.json";


private Configuration mFreemarkerConfig;
Expand All @@ -69,54 +70,72 @@ private Configuration getFreeMarkerConfig() {
}

private void loadModel(File inputDir) throws IOException, JSONException {
final File[] jsonFiles = inputDir.listFiles(new FileFilter() {
File[] entityFiles = inputDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return !pathname.getName().startsWith("_") && pathname.getName().endsWith(".json");
}
});
for (final File jsonFile : jsonFiles) {
if (Config.LOGD) Log.d(TAG, jsonFile.getCanonicalPath());
final String entityName = FilenameUtils.getBaseName(jsonFile.getCanonicalPath());
for (File entityFile : entityFiles) {
if (Config.LOGD) Log.d(TAG, entityFile.getCanonicalPath());
String entityName = FilenameUtils.getBaseName(entityFile.getCanonicalPath());
if (Config.LOGD) Log.d(TAG, "entityName=" + entityName);
final Entity entity = new Entity(entityName);
final String fileContents = FileUtils.readFileToString(jsonFile);
final JSONArray jsonArray = new JSONArray(fileContents);
final int len = jsonArray.length();
Entity entity = new Entity(entityName);
String fileContents = FileUtils.readFileToString(entityFile);
JSONObject entityJson = new JSONObject(fileContents);

// Fields
JSONArray fieldsJson = entityJson.getJSONArray("fields");
int len = fieldsJson.length();
for (int i = 0; i < len; i++) {
final JSONObject jsonObject = jsonArray.getJSONObject(i);
if (Config.LOGD) Log.d(TAG, "object=" + jsonObject);
final String fieldName = jsonObject.getString(Field.NAME);
final String fieldType = jsonObject.getString(Field.TYPE);
final Field field = new Field(fieldName, fieldType);
JSONObject fieldJson = fieldsJson.getJSONObject(i);
if (Config.LOGD) Log.d(TAG, "fieldJson=" + fieldJson);
String name = fieldJson.getString(Field.NAME);
String type = fieldJson.getString(Field.TYPE);
Field field = new Field(name, type);
entity.addField(field);
}

// Constraints (optional)
JSONArray constraintsJson = entityJson.optJSONArray("constraints");
if (constraintsJson != null) {
len = constraintsJson.length();
for (int i = 0; i < len; i++) {
JSONObject constraintJson = constraintsJson.getJSONObject(i);
if (Config.LOGD) Log.d(TAG, "constraintJson=" + constraintJson);
String name = constraintJson.getString(Constraint.NAME);
String definition = constraintJson.getString(Constraint.DEFINITION);
Constraint constraint = new Constraint(name, definition);
entity.addConstraint(constraint);
}
}

Model.get().addEntity(entity);
}
if (Config.LOGD) Log.d(TAG, Model.get().toString());
}

private JSONObject getConfig(File inputDir) throws IOException, JSONException {
if (mConfig == null) {
final File configFile = new File(inputDir, FILE_CONFIG);
final String fileContents = FileUtils.readFileToString(configFile);
File configFile = new File(inputDir, FILE_CONFIG);
String fileContents = FileUtils.readFileToString(configFile);
mConfig = new JSONObject(fileContents);
}
return mConfig;
}

private void generateColumnsFiles(Arguments arguments) throws IOException, JSONException, TemplateException {
final Template columnsTemplate = getFreeMarkerConfig().getTemplate("columns.ftl");
final JSONObject config = getConfig(arguments.inputDir);
final String packageName = config.getString("package");
Template columnsTemplate = getFreeMarkerConfig().getTemplate("columns.ftl");
JSONObject config = getConfig(arguments.inputDir);
String providerPackageName = config.getString("providerPackage");

for (final Entity entity : Model.get().getEntities()) {
final File packageDir = new File(arguments.outputDir, packageName.replace('.', '/'));
packageDir.mkdirs();
final File outputFile = new File(packageDir, entity.getNameCamelCase() + "Columns.java");
final Writer out = new OutputStreamWriter(new FileOutputStream(outputFile));
for (Entity entity : Model.get().getEntities()) {
File providerPackageDir = new File(arguments.outputDir, providerPackageName.replace('.', '/'));
providerPackageDir.mkdirs();
File outputFile = new File(providerPackageDir, entity.getNameCamelCase() + "Columns.java");
Writer out = new OutputStreamWriter(new FileOutputStream(outputFile));

final Map<String, Object> root = new HashMap<String, Object>();
Map<String, Object> root = new HashMap<String, Object>();
root.put("config", getConfig(arguments.inputDir));
root.put("entity", entity);

Expand All @@ -126,40 +145,40 @@ private void generateColumnsFiles(Arguments arguments) throws IOException, JSONE
}

private void generateContentProvider(Arguments arguments) throws IOException, JSONException, TemplateException {
final Template columnsTemplate = getFreeMarkerConfig().getTemplate("contentprovider.ftl");
final JSONObject config = getConfig(arguments.inputDir);
final String packageName = config.getString("package");
final File packageDir = new File(arguments.outputDir, packageName.replace('.', '/'));
packageDir.mkdirs();
final File outputFile = new File(packageDir, config.getString("providerClassName") + ".java");
final Writer out = new OutputStreamWriter(new FileOutputStream(outputFile));

final Map<String, Object> root = new HashMap<String, Object>();
Template columnsTemplate = getFreeMarkerConfig().getTemplate("contentprovider.ftl");
JSONObject config = getConfig(arguments.inputDir);
String providerPackageName = config.getString("providerPackage");
File providerPackageDir = new File(arguments.outputDir, providerPackageName.replace('.', '/'));
providerPackageDir.mkdirs();
File outputFile = new File(providerPackageDir, config.getString("providerClassName") + ".java");
Writer out = new OutputStreamWriter(new FileOutputStream(outputFile));

Map<String, Object> root = new HashMap<String, Object>();
root.put("config", config);
root.put("model", Model.get());

columnsTemplate.process(root, out);
}

private void generateSqliteHelper(Arguments arguments) throws IOException, JSONException, TemplateException {
final Template columnsTemplate = getFreeMarkerConfig().getTemplate("sqlitehelper.ftl");
final JSONObject config = getConfig(arguments.inputDir);
final String packageName = config.getString("package");
final File packageDir = new File(arguments.outputDir, packageName.replace('.', '/'));
packageDir.mkdirs();
final File outputFile = new File(packageDir, config.getString("sqliteHelperClassName") + ".java");
final Writer out = new OutputStreamWriter(new FileOutputStream(outputFile));

final Map<String, Object> root = new HashMap<String, Object>();
Template columnsTemplate = getFreeMarkerConfig().getTemplate("sqlitehelper.ftl");
JSONObject config = getConfig(arguments.inputDir);
String providerPackageName = config.getString("providerPackage");
File providerPackageDir = new File(arguments.outputDir, providerPackageName.replace('.', '/'));
providerPackageDir.mkdirs();
File outputFile = new File(providerPackageDir, config.getString("sqliteHelperClassName") + ".java");
Writer out = new OutputStreamWriter(new FileOutputStream(outputFile));

Map<String, Object> root = new HashMap<String, Object>();
root.put("config", config);
root.put("model", Model.get());

columnsTemplate.process(root, out);
}

private void go(String[] args) throws IOException, JSONException, TemplateException {
final Arguments arguments = new Arguments();
final JCommander jCommander = new JCommander(arguments, args);
Arguments arguments = new Arguments();
JCommander jCommander = new JCommander(arguments, args);
jCommander.setProgramName("GenerateAndroidProvider");

if (arguments.help) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright 2013 Benoit 'BoD' Lubek (BoD@JRAF.org). All Rights Reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jraf.androidcontentprovidergenerator.model;

public class Constraint {
public static final String NAME = "name";
public static final String DEFINITION = "definition";

private final String mName;
private final String mDefinition;

public Constraint(String name, String definition) {
mName = name.toLowerCase();
mDefinition = definition.toLowerCase();
}

public String getNameUpperCase() {
return mName.toUpperCase();
}

public String getDefinitionUpperCase() {
return mDefinition.toUpperCase();
}

@Override
public String toString() {
return "Constraint [mName=" + mName + ", mDefinition=" + mDefinition + "]";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
public class Entity {
private final String mName;
private final List<Field> mFields = new ArrayList<Field>();
private final List<Constraint> mConstraints = new ArrayList<Constraint>();

public Entity(String name) {
mName = name.toLowerCase();
Expand All @@ -46,6 +47,14 @@ public List<Field> getFields() {
return Collections.unmodifiableList(mFields);
}

public void addConstraint(Constraint constraint) {
mConstraints.add(constraint);
}

public List<Constraint> getConstraints() {
return Collections.unmodifiableList(mConstraints);
}

public String getNameCamelCase() {
return WordUtils.capitalizeFully(mName, new char[] { '_' }).replaceAll("_", "");
}
Expand All @@ -58,10 +67,8 @@ public String getNameUpperCase() {
return mName.toUpperCase();
}



@Override
public String toString() {
return "[" + getNameLowerCase() + ": " + mFields.toString() + "]";
return "Entity [mName=" + mName + ", mFields=" + mFields + ", mConstraints=" + mConstraints + "]";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public class Field {
public static final String TYPE = "type";

public static enum Type {
TEXT, INTEGER;
TEXT, INTEGER, BLOB;

public static Type fromString(String s) {
return valueOf(s.toUpperCase());
Expand Down Expand Up @@ -58,6 +58,6 @@ public Type getType() {

@Override
public String toString() {
return "[" + getNameLowerCase() + ": " + mType + "]";
return "Field [mName=" + mName + ", mType=" + mType + "]";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,10 @@
import java.util.List;

public class Model {
private static Model sModel;
private static final Model INSTANCE = new Model();

public synchronized static Model get() {
if (sModel == null) {
sModel = new Model();
}
return sModel;
public static Model get() {
return INSTANCE;
}

private Model() {}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package ${config.package};
package ${config.providerPackage};

import android.net.Uri;
import android.provider.BaseColumns;

import ${config.projectPackage}.Config;
import ${config.projectPackage}.Constants;

public class ${entity.nameCamelCase}Columns implements BaseColumns {
public static final String TABLE_NAME = "${entity.nameLowerCase}";
public static final Uri CONTENT_URI = Uri.parse(${config.providerClassName}.CONTENT_URI_BASE + "/" + TABLE_NAME);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package ${config.package};
package ${config.providerPackage};

import android.content.ContentProvider;
import android.content.ContentValues;
Expand All @@ -7,6 +7,10 @@ import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.provider.BaseColumns;
import android.util.Log;

import ${config.projectPackage}.Config;
import ${config.projectPackage}.Constants;

public class ${config.providerClassName} extends ContentProvider {
private static final String TAG = Constants.TAG + ${config.providerClassName}.class.getSimpleName();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package ${config.package};
package ${config.providerPackage};

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import ${config.projectPackage}.Config;
import ${config.projectPackage}.Constants;

public class ${config.sqliteHelperClassName} extends SQLiteOpenHelper {
private static final String TAG = Constants.TAG + ${config.sqliteHelperClassName}.class.getSimpleName();

Expand All @@ -19,6 +22,9 @@ public class ${config.sqliteHelperClassName} extends SQLiteOpenHelper {
<#list entity.fields as field>
+ ${entity.nameCamelCase}Columns.${field.nameUpperCase} + " ${field.type}<#if field_has_next>,</#if> "
</#list>
<#list entity.constraints as constraint>
+ ", CONSTRAINT ${constraint.nameUpperCase} ${constraint.definitionUpperCase}"
</#list>
+ " );";

</#list>
Expand Down

0 comments on commit aaffd3f

Please sign in to comment.