[英]Issue with Eclipse plugin (copying a file)
好的,所以我為Eclipse編寫了一個插件(好吧,所以它主要是從ADT復制的代碼)。 它是一個新的項目向導,與ADT的新項目向導基本相同,只是它復制到庫中,將其添加到構建路徑,並復制到其他一些文件。 一切正常。
該庫名為AltBridge,它是從App Inventor的Java Bridge庫構建的。 這個庫本質上改變了你稍微編寫一個活動的方式,我想添加一個菜單選項來創建一個新的Form(這是一個修改過的Activity)。
這就是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 /(這是在eclipse中按F11進行測試時)。
好吧,我當然把它變得比當然需要的更復雜。 這是我用過的代碼。 (我仍然不明白為什么Eclipse表現得如此奇怪......為什么在使用F11進行測試時會有效,但是在部署插件時卻沒有?)。
這也只是//創建主要活動Java文件的部分:
if (activityName != null) {
// create the main activity Java file
String activityJava = activityName + AdtConstants.DOT_JAVA;
// Get the path of the package
IPath path = ((IPackageFragment) firstElement).getPath();
String pkgpath = path.toString();
String projname = "";
// Remove the project name from the beginning of the path
String temp[] = pkgpath.split("/");
pkgpath = "";
for (int i = 1; i < temp.length; i++) {
if (i==1) {
pkgpath = "/";
projname = temp[i];
} else {
pkgpath = pkgpath + "/" + temp[i];
}
}
// Get the project
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projname);
IFile file = project.getFile(pkgpath+"/"+activityJava);
if (!file.exists()) {
try {
copyFile("java_file.template", file, java_activity_parameters);
} catch (CoreException e) {
AltBridge.log(e, "Couldn't copy the text file", pkgpath);
e.printStackTrace();
} catch (IOException e) {
AltBridge.log(e, "Couldn't copy the text file", pkgpath);
e.printStackTrace();
}
}
}
好吧,問題似乎與IProject或IFolder有關。 例如,路徑以“test / src / com / test”的形式返回。 然后,當我使用pkgfolder.getFile時,它會在路徑前添加另一個/ test /(這是在eclipse中按F11進行測試時)。
因此,如果路徑是test / src / com / test,則test必須是項目。 使用IWorkspaceRoot.findMember(path)。 並在路徑前放一個“/”。 找不到項目/文件夾等其他東西是沒有必要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.