package projectmanager;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.util.Map;
import java.util.HashMap;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class Manager {
private final IniReader config = new IniReader("C:\\xuj.ini");
private final BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
Map<String, String> path = new HashMap<>();
String selected_project = null;
public Manager() {
System.out.println("---------------------------------------");
System.out.println("| Android Project Manager |");
System.out.println("| by Vladimir Shevchuk |");
System.out.println("---------------------------------------");
checkConfig();
System.out.println("Папка: '" + path.get("PROJECTS_HOME") + "'");
System.out.println("help - справка");
enterCommand();
}
private void enterCommand() {
while(true) {
System.out.print("> ");
String command = gets();
switch(command.toLowerCase()) {
case "help":
printHelp();
break;
case "remove":
removeProject();
break;
case "build":
buildProject();
break;
case "create":
createProject();
break;
case "show":
showProjects();
break;
case "exit":
System.out.println("\nВсего хорошего! ;-)");
System.exit(0);
break;
default:
System.out.println("Неверная команда!");
}
}
}
private void showProjects() {
File[] pjs = new File(path.get("PROJECTS_HOME")).listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
});
if(pjs.length == 0) {
System.out.println("\tВы не создали ни одного проекта!");
return;
}
for(int i = 0; i < pjs.length; i++)
System.out.println("\t" + (i + 1) + ". " + pjs[0].getName());
}
private void removeProject() {
}
private void selectProject() {
System.out.print("\tНазвание проекта: ");
String proj = null;
try{
proj = cin.readLine();
}catch(IOException io){}
String pj_conf_ini = path.get("PROJECTS_HOME") + "/" + proj + "/Project.ini";
if(!new File(pj_conf_ini).exists()) {
System.out.println("\tНе найдена конфигурация проекта!");
return;
}
this.selected_project = proj;
}
private void buildProject() {
if(this.selected_project == null) {
System.out.println("Выберите проект для работы командой select");
return;
}
String proj = this.selected_project;
String pj_conf_ini = path.get("PROJECTS_HOME") + "/" + proj + "/Project.ini";
if(!new File(pj_conf_ini).exists()) {
System.out.println("Не найдена конфигурация проекта!");
return;
}
IniReader pj_conf = new IniReader(pj_conf_ini);
String api = pj_conf.get("Config", "API");
System.out.print("\tГенерируем R.java: ");
String result = exec(path.get("BUILD_TOOLS_PATH") + "/aapt package -f -m -S \"" + path.get("PROJECTS_HOME") + "/" + proj + "/res\" -J \"" + path.get("PROJECTS_HOME") + "/" + proj + "/src\" -M \"" + path.get("PROJECTS_HOME") + "/" + proj + "/AndroidManifest.xml\" -I \"" + path.get("SDK_HOME") + "/platforms/android-" + api + "/android.jar\"").trim();
if(result.equals(""))
System.out.println("Успех!");
else {
System.out.println("Ошибка!");
System.out.println("----------");
System.out.println(result);
System.out.println("----------");
return;
}
System.out.print("\tКомпилируем: ");
String pgp = pj_conf.get("Config", "Package").replace(".", "/");
result = exec(path.get("JDK_HOME") + "/bin/javac -d \"" + path.get("PROJECTS_HOME") + "/" + proj + "/obj\" -cp \"" + path.get("SDK_HOME") + "/platforms/android-" + api + "/android.jar\" -sourcepath \"" + path.get("PROJECTS_HOME") + "/" + proj + "/src\" " + path.get("PROJECTS_HOME") + "/" + proj + "/src/" + pgp + "/*.java").trim();
if(result.equals(""))
System.out.println("Успех!");
else {
System.out.println("Ошибка!");
System.out.println("----------");
System.out.println(result);
System.out.println("----------");
return;
}
System.out.print("\tСобираем в .dex: ");
result = exec(path.get("BUILD_TOOLS_PATH") + "/dx.bat --dex --output=\"" + path.get("PROJECTS_HOME") + "/" + proj + "/bin/classes.dex\" " + path.get("PROJECTS_HOME") + "/" + proj + "/obj");
if(result.equals(""))
System.out.println("Успех!");
else {
System.out.println("Ошибка!");
System.out.println("----------");
System.out.println(result);
System.out.println("----------");
return;
}
System.out.print("\tСобираем в APK: ");
result = exec(path.get("BUILD_TOOLS_PATH") + "/aapt package -f -M \"" + path.get("PROJECTS_HOME") + "/" + proj + "/AndroidManifest.xml\" -S \"" + path.get("PROJECTS_HOME") + "/" + proj + "/res\" -I \"" + path.get("SDK_HOME") + "/platforms/android-" + api + "/android.jar\" -F \"" + path.get("PROJECTS_HOME") + "/" + proj + "/bin/" + proj + ".unsigned.apk\" \"" + path.get("PROJECTS_HOME") + "/" + proj + "/bin\"");
if(result.equals(""))
System.out.println("Успех!");
else {
System.out.println("Ошибка!");
System.out.println("----------");
System.out.println(result);
System.out.println("----------");
return;
}
System.out.print("\tСоздаём keystore: ");
exec(path.get("JDK_HOME") + "/bin/keytool -genkey -validity 10000 -dname \"CN=AndroidDebug, O=Android, C=US\" -keystore " + path.get("PROJECTS_HOME") + "/" + proj + "/" + proj + ".keystore -storepass android -keypass android -alias androiddebugkey -keyalg RSA -v -keysize 2048");
System.out.println("Успех!");
System.out.print("\tПодписываем APK: ");
result = exec(path.get("JDK_HOME") + "/bin/jarsigner -sigalg SHA1withRSA -digestalg SHA1 -keystore " + path.get("PROJECTS_HOME") + "/" + proj + "/" + proj + ".keystore -storepass android -keypass android -signedjar \"" + path.get("PROJECTS_HOME") + "/" + proj + "/bin/" + proj + ".apk\" \"" + path.get("PROJECTS_HOME") + "/" + proj + "/bin/" + proj + ".unsigned.apk\" androiddebugkey");
System.out.println("Успех!");
System.out.print("\tЧистим мусор: ");
//coming soon...
System.out.println("Успех!");
}
private String exec(String command) {
Runtime runtime = Runtime.getRuntime();
StringBuilder content = new StringBuilder();
try {
Process process = runtime.exec(command);
InputStream is = process.getErrorStream() != null ? process.getErrorStream() : process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
content.append(line);
content.append("\n");
}
}catch(Exception e){
System.out.println("Системная ошибка!");
e.printStackTrace();
System.exit(0);
}
return content.toString();
}
private void createProject() {
System.out.print("Название проекта(TestProject): ");
String project_name = gets();
System.out.print("Package(com.example.test): ");
String app_package = gets();
System.out.print("Activity name(MainActivity): ");
String activity = gets();
System.out.print("API Level(19): ");
String api = gets();
if(project_name.equals(""))
project_name = "TestProject";
if(app_package.equals(""))
app_package = "com.example.test";
if(activity.equals(""))
activity = "MainActivity";
if(api.equals(""))
api = "19";
if(!new File(path.get("SDK_HOME") + "/platforms/android-" + api + "/android.jar").exists()) {
System.out.println("android.jar для API " + api + " не найдено!");
System.exit(0);
}
if(new File(path.get("PROJECTS_HOME") + "/" + project_name).exists()) {
System.out.println("Проект с таким названием уже существует!");
return;
}
if(!new File(path.get("PROJECTS_HOME") + "/" + project_name).mkdir()) {
System.out.println("Невозможно создать проект с таким названием, или запись в папку запрещена!");
return;
}
String project_path = path.get("PROJECTS_HOME") + "/" + project_name + "/";
writeFile(project_path + "AndroidManifest.xml", getResource("AndroidManifest").replace("{package}", app_package).replace("{api}", api).replace("{project}", project_name).replace("{activity}", activity));
new File(project_path + "bin").mkdir();
new File(project_path + "obj").mkdir();
new File(project_path + "res").mkdir();
new File(project_path + "src").mkdir();
new File(project_path + "res/values").mkdir();
writeFile(project_path + "res/values/strings.xml", getResource("strings"));
StringBuilder curr = new StringBuilder(project_path + "src/");
String[] p = app_package.split("\\.");
for(String d : p) {
curr.append(d);
curr.append("/");
new File(curr.toString()).mkdir();
}
writeFile(curr.toString() + activity + ".java", getResource("Activity").replace("{package}", app_package).replace("{activity}", activity));
writeFile(project_path + "Project.ini", "[Config]\nAPI = " + api + "\nPackage = " + app_package);
System.out.println("Проект '" + project_name + "' успешно создан!");
}
private void writeFile(String fileName, String text) {
try {
PrintWriter out = new PrintWriter(new File(fileName).getAbsoluteFile());
try {
out.print(text);
} finally {
out.close();
}
} catch(IOException e) {
System.out.println("Системная ошибка!");
System.exit(0);
}
}
private String gets() {
try {
return cin.readLine();
}catch(IOException io) {
System.out.println("Системная ошибка!");
System.exit(0);
}
return null;
}
private String getResource(String file) {
DataInputStream dis = new DataInputStream(getClass().getResourceAsStream("/resources/" + file));
StringBuilder strBuff = new StringBuilder();
int ch = 0;
try {
while ((ch = dis.read()) != -1) {
strBuff.append((char) ((ch >= 0xc0 && ch <= 0xFF) ? (ch + 0x350) : ch));
}
dis.close();
} catch (Exception e) {
System.err.println("ERROR!");
System.exit(0);
}
return strBuff.toString();
}
private void printHelp() {
String[] commands = {
"help - справка",
"exit - выход",
"show - показать проекты",
"create - создать проект",
"remove - удалить проект",
"build - собрать проект"
};
for(String command : commands)
System.out.println("\t" + command);
}
private void checkConfig() {
boolean error = false;
if(!new File(config.get("Path", "JDK_HOME")).exists()) {
System.out.println("Папка с JDK не найдена!");
error = true;
}else
path.put("JDK_HOME", config.get("Path", "JDK_HOME"));
if(!new File(config.get("Path", "SDK_HOME")).exists()) {
System.out.println("Папка с Android SDK не найдена!");
error = true;
}else
path.put("SDK_HOME", config.get("Path", "SDK_HOME"));
if(!new File(config.get("Path", "PROJECTS_HOME")).exists()) {
System.out.println("Папка с проектами не найдена!");
error = true;
}else
path.put("PROJECTS_HOME", config.get("Path", "PROJECTS_HOME"));
if(!new File(config.get("Path", "SDK_HOME") + "/build-tools/" ).exists()) {
System.out.println("Папка build-tools в Android SDK не найдена!");
error = true;
}
if(error) {
System.out.println("\nПроверьте настройки в файле config.ini и запустите программу ещё раз!");
System.exit(0);
}
error = false;
String btv = getLatestBuildToolsVersion(new File(path.get("SDK_HOME") + "/build-tools/"));
if(btv != null)
path.put("BUILD_TOOLS_PATH", path.get("SDK_HOME") + "/build-tools/" + btv);
else {
System.out.println("Не найдено инструментов " + path.get("SDK_HOME") + "/build-tools/");
System.exit(0);
}
String[] checkFiles = {
path.get("BUILD_TOOLS_PATH") + "/aapt.exe",
path.get("BUILD_TOOLS_PATH") + "/dx.bat",
path.get("SDK_HOME") + "/platform-tools/adb.exe",
path.get("JDK_HOME") + "/bin/javac.exe",
path.get("JDK_HOME") + "/bin/keytool.exe",
path.get("JDK_HOME") + "/bin/jarsigner.exe"
};
for(String file : checkFiles)
if(!new File(file).exists()) {
System.out.println("Файл '" + file + "' не найден!");
error = true;
}
if(error)
System.exit(0);
}
private String getLatestBuildToolsVersion(File path) {
File[] dirs = path.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
});
for(int i = dirs.length - 1; i >= 0; i--)
try {
Integer.parseInt(dirs[i].getName().substring(0,1));
return dirs[i].getName();
}catch(NumberFormatException numex) {}
return null;
}
}