Хорошо, поэтому я написал плагин для Eclipse (хорошо, так что это в основном скопированный код из ADT).Это новый мастер проектов, который по сути аналогичен новому мастеру проектов ADT, только копирует библиотеку, добавляет ее в путь сборки и копирует некоторые другие файлы.Все это прекрасно работает.
Библиотека называется AltBridge, которая была построена из библиотеки Java Bridge App Inventor.Эта библиотека немного меняет то, как вы пишете действие, и я хотел добавить опцию меню, чтобы создать новую форму (которая является измененным действием).
Вот где Eclipse вызывает беспокойство.Я получил, чтобы он работал нормально, если я нажму F11.Это создает новый файл без проблем.Тем не менее, когда я экспортирую плагин и пробую его, он не работает.
Вот что у меня есть до сих пор:
public class NewFormMenuSelection extends AbstractHandler implements IHandler {
private static final String PARAM_PACKAGE = "PACKAGE";
private static final String PARAM_ACTIVITY = "ACTIVITY_NAME";
private static final String PARAM_IMPORT_RESOURCE_CLASS = "IMPORT_RESOURCE_CLASS";
private Map<String, Object> java_activity_parameters = new HashMap<String, Object>();
public Object execute(ExecutionEvent event) throws ExecutionException {
IStructuredSelection selection = (IStructuredSelection) HandlerUtil
.getActiveMenuSelection(event);
String directory = "";
Object firstElement = selection.getFirstElement();
if (firstElement instanceof IPackageFragment) {
InputDialog dialog = new InputDialog(HandlerUtil.getActiveShell(event), "Name of the new Form to create?", "Please enter the name of the new form to create.", "NewForm", null);
if ( dialog.open()==IStatus.OK ) {
String activityName = dialog.getValue();
String packageName = ((IPackageFragment) firstElement).getElementName();
if (activityName != null) {
String resourcePackageClass = null;
// An activity name can be of the form ".package.Class", ".Class" or FQDN.
// The initial dot is ignored, as it is always added later in the templates.
int lastDotIndex = activityName.lastIndexOf('.');
if (lastDotIndex != -1) {
// Resource class
if (lastDotIndex > 0) {
resourcePackageClass = packageName + "." + AdtConstants.FN_RESOURCE_BASE; //$NON-NLS-1$
}
// Package name
if (activityName.startsWith(".")) { //$NON-NLS-1$
packageName += activityName.substring(0, lastDotIndex);
} else {
packageName = activityName.substring(0, lastDotIndex);
}
// Activity Class name
activityName = activityName.substring(lastDotIndex + 1);
}
java_activity_parameters.put(PARAM_IMPORT_RESOURCE_CLASS, "");
java_activity_parameters.put(PARAM_ACTIVITY, activityName);
java_activity_parameters.put(PARAM_PACKAGE, packageName);
if (resourcePackageClass != null) {
String importResourceClass = "\nimport " + resourcePackageClass + ";"; //$NON-NLS-1$ // $NON-NLS-2$
java_activity_parameters.put(PARAM_IMPORT_RESOURCE_CLASS, importResourceClass);
}
if (activityName != null) {
// create the main activity Java file
// get the path of the package
IPath path = ((IPackageFragment) firstElement).getPath();
String pkgpath = path.toString();
// Get the project name
String activityJava = activityName + AdtConstants.DOT_JAVA;
String projname = ((IPackageFragment) firstElement).getParent().getJavaProject().getElementName();
// Get the project
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projname);
IFolder pkgFolder = project.getFolder(pkgpath);
IFile file = pkgFolder.getFile(activityJava);
if (!file.exists()) {
try {
copyFile("java_file.template", file, java_activity_parameters, false);
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
return null;
}
private void copyFile(String resourceFilename, IFile destFile,
Map<String, Object> parameters, boolean reformat)
throws CoreException, IOException {
// Read existing file.
String template = AltBridge.readEmbeddedTextFile(
"templates/" + resourceFilename);
// Replace all keyword parameters
template = replaceParameters(template, parameters);
if (reformat) {
// Guess the formatting style based on the file location
XmlFormatStyle style = XmlFormatStyle.getForFile(destFile.getProjectRelativePath());
if (style != null) {
template = reformat(style, template);
}
}
// Save in the project as UTF-8
InputStream stream = new ByteArrayInputStream(template.getBytes("UTF-8")); //$NON-NLS-1$
destFile.create(stream, true /* force */, null);
}
private String replaceParameters(String str, Map<String, Object> parameters) {
if (parameters == null) {
AltBridge.log(IStatus.ERROR,
"NPW replace parameters: null parameter map. String: '%s'", str); //$NON-NLS-1$
return str;
} else if (str == null) {
AltBridge.log(IStatus.ERROR,
"NPW replace parameters: null template string"); //$NON-NLS-1$
return str;
}
for (Entry<String, Object> entry : parameters.entrySet()) {
if (entry != null && entry.getValue() instanceof String) {
Object value = entry.getValue();
if (value == null) {
AltBridge.log(IStatus.ERROR,
"NPW replace parameters: null value for key '%s' in template '%s'", //$NON-NLS-1$
entry.getKey(),
str);
} else {
str = str.replaceAll(entry.getKey(), (String) value);
}
}
}
return str;
}
private String reformat(XmlFormatStyle style, String contents) {
if (AdtPrefs.getPrefs().getUseCustomXmlFormatter()) {
XmlFormatPreferences formatPrefs = XmlFormatPreferences.create();
return XmlPrettyPrinter.prettyPrint(contents, formatPrefs, style,
null /*lineSeparator*/);
} else {
return contents;
}
}
Часть, с которой у меня, похоже, проблеманаходится под тем, где написано // создать основной файл активности Java.
Чтобы заставить его работать при нажатии F11, мне пришлось отбросить первые две записи пакета (я знаю, что, возможно, мог бы сделатьэто лучший способ, но это работает).В противном случае по какой-то причине он добавил имя проекта в путь в начале (удвоив его).Если оставить этот путь, он не будет работать при экспорте и попытке вне среды тестирования.Это дает ошибку, говоря, что имя проекта должно быть в пути.Так что, если я удаляю раздел, который пропускает это, он не работает при нажатии F11, а за пределами среды сборки, он не работает и не дает никаких ошибок.Любые подсказки о том, что я могу делать не так?
Вот код файла копии (опять же, это просто скопировано из плагина ADT):
public static String readEmbeddedTextFile(String filepath) {
try {
InputStream is = readEmbeddedFileAsStream(filepath);
if (is != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder total = new StringBuilder(reader.readLine());
while ((line = reader.readLine()) != null) {
total.append('\n');
total.append(line);
}
return total.toString();
}
} catch (IOException e) {
// we'll just return null
AltBridge.log(e, "Failed to read text file '%s'", filepath); //$NON-NLS-1$
}
return null;
}
public static InputStream readEmbeddedFileAsStream(String filepath) {
// attempt to read an embedded file
try {
URL url = getEmbeddedFileUrl(AdtConstants.WS_SEP + filepath);
if (url != null) {
return url.openStream();
}
} catch (MalformedURLException e) {
// we'll just return null.
AltBridge.log(e, "Failed to read stream '%s'", filepath); //$NON-NLS-1$
} catch (IOException e) {
// we'll just return null;.
AltBridge.log(e, "Failed to read stream '%s'", filepath); //$NON-NLS-1$
}
return null;
}
public static URL getEmbeddedFileUrl(String filepath) {
Bundle bundle = null;
synchronized (AltBridge.class) {
if (plugin != null) {
bundle = plugin.getBundle();
} else {
AltBridge.log(IStatus.WARNING, "ADT Plugin is missing"); //$NON-NLS-1$
return null;
}
}
// attempt to get a file to one of the template.
String path = filepath;
if (!path.startsWith(AdtConstants.WS_SEP)) {
path = AdtConstants.WS_SEP + path;
}
URL url = bundle.getEntry(path);
if (url == null) {
AltBridge.log(IStatus.INFO, "Bundle file URL not found at path '%s'", path); //$NON-NLS-1$
}
return url;
}
Хорошо, похоже, проблемас IProject или IFolder.Путь возвращается как "test / src / com / test", например.Затем, когда я использую pkgfolder.getFile, он добавляет еще один / test / перед путем (это при тестировании путем нажатия F11 в eclipse).