Example usage for org.eclipse.jdt.core IJavaProject findPackageFragment

List of usage examples for org.eclipse.jdt.core IJavaProject findPackageFragment

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IJavaProject findPackageFragment.

Prototype

IPackageFragment findPackageFragment(IPath path) throws JavaModelException;

Source Link

Document

Returns the first existing package fragment on this project's classpath whose path matches the given (absolute) path, or null if none exist.

Usage

From source file:co.turnus.widgets.util.WidgetsUtils.java

License:Open Source License

/**
 * Returns the qualified name of the given file, i.e. qualified.name.of.File
 * for <code>/project/sourceFolder/qualified/name/of/File.fileExt</code> or
 * <code>/project/outputFolder/qualified/name/of/File.fileExt</code>.
 * // w ww  .  ja v  a2 s.com
 * @param file
 *            a file
 * @return a qualified name, or <code>null</code> if the file is not in a
 *         source folder
 */
public static String getQualifiedName(IFile file) {
    IProject project = file.getProject();

    IJavaProject javaProject = JavaCore.create(project);
    if (!javaProject.exists()) {
        return null;
    }

    try {
        IPath path = file.getParent().getFullPath();
        IPackageFragment fragment = null;
        if (javaProject.getOutputLocation().isPrefixOf(path)) {
            // create relative path
            int count = path.matchingFirstSegments(javaProject.getOutputLocation());
            IPath relPath = path.removeFirstSegments(count);

            // creates full path to source
            for (IFolder folder : getSourceFolders(project)) {
                path = folder.getFullPath().append(relPath);
                fragment = javaProject.findPackageFragment(path);
                if (fragment != null) {
                    break;
                }
            }
        } else {
            fragment = javaProject.findPackageFragment(path);
        }

        if (fragment == null) {
            return null;
        }

        String name = file.getFullPath().removeFileExtension().lastSegment();
        if (fragment.isDefaultPackage()) {
            // handles the default package case
            return name;
        }
        return fragment.getElementName() + "." + name;
    } catch (JavaModelException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.android.ide.eclipse.adt.internal.refactoring.core.AndroidPackageRenameParticipant.java

License:Open Source License

/**
 * Return the gen package fragment//w w  w .j a v a2  s  . c om
 *
 */
private IPackageFragment getGenPackageFragment() throws JavaModelException {
    IJavaProject javaProject = (IJavaProject) mPackageFragment.getAncestor(IJavaElement.JAVA_PROJECT);
    if (javaProject != null && javaProject.isOpen()) {
        IProject project = javaProject.getProject();
        IFolder genFolder = project.getFolder(SdkConstants.FD_GEN_SOURCES);
        if (genFolder.exists()) {
            String javaPackagePath = mAppPackage.replace(".", "/");
            IPath genJavaPackagePath = genFolder.getFullPath().append(javaPackagePath);
            IPackageFragment genPackageFragment = javaProject.findPackageFragment(genJavaPackagePath);
            return genPackageFragment;
        }
    }
    return null;
}

From source file:com.android.ide.eclipse.adt.internal.refactorings.core.AndroidPackageRenameParticipant.java

License:Open Source License

/**
 * Return the gen package fragment/*from   w  w  w.j  a  v a  2  s . c om*/
 */
private IPackageFragment getGenPackageFragment() throws JavaModelException {
    IJavaProject javaProject = (IJavaProject) mPackageFragment.getAncestor(IJavaElement.JAVA_PROJECT);
    if (javaProject != null && javaProject.isOpen()) {
        IProject project = javaProject.getProject();
        IFolder genFolder = project.getFolder(SdkConstants.FD_GEN_SOURCES);
        if (genFolder.exists()) {
            String javaPackagePath = mAppPackage.replace('.', '/');
            IPath genJavaPackagePath = genFolder.getFullPath().append(javaPackagePath);
            IPackageFragment genPackageFragment = javaProject.findPackageFragment(genJavaPackagePath);
            return genPackageFragment;
        }
    }
    return null;
}

From source file:com.centurylink.mdw.plugin.designer.properties.OsgiAdapterDesignSection.java

License:Apache License

private ICompilationUnit getCompilationUnit(WorkflowAsset asset) throws JavaModelException {
    IJavaProject javaProj = activity.getProject().getJavaProject();
    IPackageFragment javaPkg = (IPackageFragment) javaProj
            .findPackageFragment(asset.getTempFolder().getFullPath());
    if (javaPkg.exists()) {
        for (ICompilationUnit compUnit : javaPkg.getCompilationUnits()) {
            if (compUnit.getElementName().equals(asset.getName())) {
                return compUnit;
            }// w  ww  .j  a va 2  s. com
        }
    }
    return null;
}

From source file:com.google.gdt.eclipse.designer.core.nls.GwtSourceTest.java

License:Open Source License

@DisposeProjectAfter
public void test_create() throws Exception {
    // recreate project
    {// w ww .  jav a  2 s  .c o  m
        tearDown();
        do_projectDispose();
        setUp();
    }
    // parse
    RootPanelInfo frame = parseJavaInfo("public class Test implements EntryPoint {",
            "  public void onModuleLoad() {", "    RootPanel rootPanel = RootPanel.get();",
            "    rootPanel.setTitle('My title');", "  }", "}");
    NlsSupport support = NlsSupport.get(frame);
    IEditableSupport editableSupport = support.getEditable();
    // prepare editable source
    IEditableSource editableSource = NlsTestUtils.createEmptyEditable("test.client.MyConstants");
    editableSource.setKeyGeneratorStrategy(GwtSource.GWT_KEY_GENERATOR);
    // prepare parameters
    SourceParameters parameters = new SourceParameters();
    IJavaProject javaProject = m_lastEditor.getJavaProject();
    {
        parameters.m_constant = new SourceClassParameters();
        SourceClassParameters constant = parameters.m_constant;
        constant.m_sourceFolder = javaProject.findPackageFragmentRoot(new Path("/TestProject/src"));
        constant.m_package = javaProject.findPackageFragment(new Path("/TestProject/src/test/client"));
        constant.m_packageFolder = (IFolder) constant.m_package.getUnderlyingResource();
        constant.m_packageName = constant.m_package.getElementName();
        constant.m_className = "MyConstants";
        constant.m_fullClassName = "test.client.MyConstants";
        constant.m_exists = false;
    }
    parameters.m_fieldName = "CONSTANTS";
    // add source
    {
        SourceDescription sourceDescription = new SourceDescription(GwtSource.class,
                GwtSourceNewComposite.class);
        editableSupport.addSource(editableSource, sourceDescription, parameters);
    }
    // do externalize
    StringPropertyInfo propertyInfo = editableSupport.getProperties(frame).get(0);
    editableSupport.externalizeProperty(propertyInfo, editableSource, true);
    // apply commands
    support.applyEditable(editableSupport);
    // checks
    assertEditor("public class Test implements EntryPoint {",
            "  private static final MyConstants CONSTANTS = GWT.create(MyConstants.class);",
            "  public void onModuleLoad() {", "    RootPanel rootPanel = RootPanel.get();",
            "    rootPanel.setTitle(CONSTANTS.rootPanel_title());", "  }", "}");
    // Constants
    {
        String messages = getFileContentSrc("test/client/MyConstants.java");
        messages = StringUtils.replace(messages, "\r\n", "\n");
        assertEquals(
                getSourceDQ("package test.client;", "", "import com.google.gwt.i18n.client.Constants;", "",
                        "public interface MyConstants extends Constants {", "  String rootPanel_title();", "}"),
                messages);
    }
    // *.properties
    {
        String newProperties = getFileContentSrc("test/client/MyConstants.properties");
        assertTrue(newProperties.contains("#GWT variable: CONSTANTS"));
        assertTrue(newProperties.contains("rootPanel_title=My title"));
    }
    // module
    {
        String module = getFileContentSrc("test/Module.gwt.xml");
        assertTrue(module.contains("com.google.gwt.i18n.I18N"));
    }
    // refresh, check that CONSTANTS is used and setTitle() executed
    {
        frame.refresh();
        assertEquals("My title", ReflectionUtils.invokeMethod(frame.getObject(), "getTitle()"));
    }
    // execute scheduled actions
    waitEventLoop(0);
}

From source file:com.google.gwt.eclipse.core.clientbundle.ClientBundleResource.java

License:Open Source License

private String getSourceAnnotationValue(IType clientBundle) throws JavaModelException {
    IJavaProject javaProject = clientBundle.getJavaProject();
    assert (javaProject.isOnClasspath(file));

    IPackageFragment resourcePckg = javaProject.findPackageFragment(file.getParent().getFullPath());

    // If the resource is not in the same package as our ClientBundle, we need
    // an @Source with the full classpath-relative path to the resource.
    if (!clientBundle.getPackageFragment().equals(resourcePckg)) {
        return ResourceUtils.getClasspathRelativePath(resourcePckg, file.getName()).toString();
    }//from   w ww .j  a  va 2 s  .co  m

    // If the resource has a different name than the method, we need an @Source,
    // although in this case we don't need the full path.
    String fileNameWithoutExt = ResourceUtils.filenameWithoutExtension(file);
    if (!ResourceUtils.areFilenamesEqual(fileNameWithoutExt, methodName)) {
        return file.getName();
    }

    // If resource doesn't have one of the default extensions, we need @Source.
    IType resourceType = JavaModelSearch.findType(javaProject, resourceTypeName);
    if (!hasDefaultExtension(file, resourceType)) {
        return file.getName();
    }

    // If the resource is in ClientBundle package and its name (without file
    // extension) matches the method name, no need for @Source
    return null;
}

From source file:com.google.gwt.eclipse.core.modules.ModuleFile.java

License:Open Source License

/**
 * Get the GWT Maven Module package from GWT plugin 2 module.gwt.xml.
 *
 * @param project/*from  w ww  .  j a v a 2  s  .co m*/
 * @return the module path
 */
private IJavaElement getGwtMavenModuleNameForGwtMavenPlugin2(IProject project) {
    if (project == null) {
        return null;
    }

    IFolder moduleFolder = (IFolder) getFile().getParent();

    // For GWT maven plugin 2, its module is in src/main
    if (!moduleFolder.toString().contains("src/main")) {
        return null;
    }

    IJavaProject javaProject = JavaCore.create(project);
    if (javaProject == null) {
        return null;
    }

    String moduleName = WebAppProjectProperties.getGwtMavenModuleName(project);
    if (moduleName == null || !moduleName.contains(".")) {
        return null;
    }

    String[] moduleNameParts = moduleName.split("\\.");

    IPath path = moduleFolder.getFullPath().append("java");
    for (int i = 0; i < moduleNameParts.length - 1; i++) {
        path = path.append(moduleNameParts[i]);
    }

    try {
        return javaProject.findPackageFragment(path);
    } catch (JavaModelException e) {
        return null;
    }
}

From source file:com.google.gwt.eclipse.core.modules.ModuleFile.java

License:Open Source License

/**
 * Find the Source folder for the src/main/.../client
 *
 * TODO won't work b/c super source could have a client, or some other path before it.
 *
 * @param moduleFolder/*from w  w w.ja  va  2s  .  c  om*/
 * @return The source package java for client
 */
private IJavaElement findSourceFolderElement(IFolder moduleFolder) {
    // TODO red the source attrbute in the module and find it?
    IFolder folderSourcePackage = findSourcePackage(moduleFolder, "client");
    if (folderSourcePackage == null) {
        return null;
    }

    IJavaProject javaProject = JavaCore.create(folderSourcePackage.getProject());
    if (javaProject == null) {
        return null;
    }

    try {
        IPackageFragment clientPackage = javaProject.findPackageFragment(folderSourcePackage.getFullPath());
        return clientPackage;
    } catch (JavaModelException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:edu.brown.cs.bubbles.bedrock.BedrockJava.java

License:Open Source License

/********************************************************************************/

void handleFindHierarchy(String proj, String pkg, String cls, boolean all, IvyXmlWriter xw)
        throws BedrockException {
    IJavaProject ijp = getJavaProject(proj);
    IRegion rgn = JavaCore.newRegion();//from w  w w.  j  a  v a  2 s  .c  o  m
    IType fortype = null;

    boolean havejp = (ijp != null);

    if (ijp == null && (pkg != null || cls != null)) {
        IJavaElement[] aps = getAllProjects();
        if (aps.length == 0)
            return;
        if (cls != null) {
            for (IJavaElement ije : aps) {
                IJavaProject xjp = ije.getJavaProject();
                try {
                    if (xjp.findType(cls) != null) {
                        ijp = xjp;
                        break;
                    }
                } catch (JavaModelException e) {
                }
            }
        }
        if (ijp == null)
            ijp = aps[0].getJavaProject();
    }

    int addct = 0;

    if (cls != null && ijp != null) {
        try {
            IType typ = ijp.findType(cls);
            fortype = typ;
            // rgn.add(typ);
            // ++addct;
        } catch (JavaModelException e) {
            BedrockPlugin.logE("Problem getting type by name: " + e);
        }
    }

    if (pkg != null && ijp != null) {
        String ppth = "/" + pkg.replace(".", "/");
        try {
            for (IPackageFragmentRoot ipr : ijp.getPackageFragmentRoots()) {
                IPath rpath = ipr.getPath();
                Path npath = new Path(rpath.toString() + ppth);
                IPackageFragment ipf = ijp.findPackageFragment(npath);
                if (ipf != null) {
                    rgn.add(ipf);
                    ++addct;
                }
            }
        } catch (Exception e) {
            BedrockPlugin.logE("Problem getting package fragments for " + ppth + ": " + e);
        }
    } else if (havejp && ijp != null) {
        if (all) {
            rgn.add(ijp);
            ++addct;
        } else {
            try {
                for (IPackageFragment ipf : ijp.getPackageFragments()) {
                    for (ICompilationUnit icu : ipf.getCompilationUnits()) {
                        IType ity = ((ITypeRoot) icu).findPrimaryType();
                        if (ity != null) {
                            rgn.add(ity);
                            ++addct;
                        }
                    }
                }
            } catch (Throwable e) {
                BedrockPlugin.logE("Problem getting package fragments: " + e);
            }
        }
    } else {
        for (IJavaElement pi : getAllProjects()) {
            IJavaProject xjp = pi.getJavaProject();
            if (xjp != null && !rgn.contains(xjp)) {
                rgn.add(xjp);
                ++addct;
            }
            // String pnm = pi.getJavaProject().getProject().getName();
            // handleFindHierarchy(pnm,null,null,all,xw);
        }
    }

    if (addct > 0 && ijp != null) {
        try {
            BedrockPlugin.logD("FIND TYPE HIERARCHY FOR " + fortype + " " + addct + " " + rgn);

            ITypeHierarchy ith;
            if (fortype != null)
                ith = ijp.newTypeHierarchy(fortype, rgn, null);
            else
                ith = ijp.newTypeHierarchy(rgn, null);
            BedrockUtil.outputTypeHierarchy(ith, xw);
        } catch (JavaModelException e) {
            BedrockPlugin.logE("Problem outputing type hierarchy: " + e);
        } catch (NullPointerException e) {
            // this is a bug in Eclipse that should be fixed
        }
    }
}

From source file:in.cypal.studio.gwt.ui.wizards.NewGwtEntryPointClassWizardPage.java

License:Apache License

public IPackageFragment getPackageFragment() {
    IPackageFragment packageFragment = null;
    if (!projectText.equals("")) {//$NON-NLS-1$
        try {// w w  w  . jav a 2 s. co m
            IJavaProject project = JavaCore.create(Util.getProject(projectText));
            IPath moduleXmlPath = new Path(moduleText);
            IPath packageFragmentPath = new Path("/").append(projectText) //$NON-NLS-1$
                    .append(moduleXmlPath.removeLastSegments(1));
            packageFragmentPath = packageFragmentPath.append("client");//$NON-NLS-1$
            packageFragment = project.findPackageFragment(packageFragmentPath);
        } catch (JavaModelException e) {
            Activator.logException(e);
        }
    }
    return packageFragment;
}