java - Eclipse 插件问题(复制文件)

标签 java eclipse plugins

好吧,我已经为 Eclipse 写了一个插件(好吧,它主要是从 ADT 复制代码)。它是一个新的项目向导,其功能与 ADT 的新项目向导基本相同,只是它复制了一个库,将其添加到构建路径,并复制了一些其他文件。这一切都很好。

该库称为 AltBridge,它是从 App Inventor 的 Java Bridge 库构建的。这个库本质上改变了你编写 Activity 的方式,我想添加一个菜单选项来创建一个新的表单(这是一个修改过的 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;
   }
}

我似乎遇到问题的部分是在它说//创建主要 Activity 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 进行测试时可以工作,但在部署插件时却不能?)。

这也只是//创建主要 Activity 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();
        }
    }
}

关于java - Eclipse 插件问题(复制文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8524849/

相关文章:

Android 4.3 虚拟设备 CPU/ABI - 未安装系统镜像 (eclipse)

Eclipse 在 Tomcat 上部署未经过滤的 .WAR-Archive

java - 如何在 Eclipse 中分析 Eclipse 应用程序?

java - 需要使用 XSLT 或通过 java 代码将 pdf 转换为 xml 或 html

java - 在 Eclipse 中从 2.4 升级 Gradle 版本

java - 在运行时交换正在运行的 jar

java - 在同一项目中本地应用自定义 gradle 插件

plugins - 在 Sublime Text 中显示事件插件并禁用它们

java - IntelliJ 正确使用库

java - 如何解决 'threads cannot be resolved to a variable'错误?