Example usage for org.eclipse.jdt.core IPackageFragmentRoot getPackageFragment

List of usage examples for org.eclipse.jdt.core IPackageFragmentRoot getPackageFragment

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IPackageFragmentRoot getPackageFragment.

Prototype

IPackageFragment getPackageFragment(String packageName);

Source Link

Document

Returns the package fragment with the given package name.

Usage

From source file:org.apache.tapestrytools.ui.internal.wizards.AddTapestryPageWizard.java

License:Open Source License

/**
 * The worker method. It will find the container, create the file if missing
 * or just replace its contents, and open the editor on the newly created
 * file./*from www  .j a v  a 2s.  co m*/
 */
private void doFinish(String projectName, String folderName, String packageName, String className,
        IProgressMonitor monitor) throws CoreException {
    IProject project = ResourcesPlugin.getWorkspace().getRoot().findMember(projectName).getProject();//ProjectUtilities.getProject(projectName);
    IJavaProject javaProject = JavaCore.create(project);
    IPackageFragmentRoot src = null;
    IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
    for (IPackageFragmentRoot pfr : roots) {
        if (pfr.getPath().toString().equals(folderName)) {
            src = pfr;
            break;
        }
    }
    monitor.beginTask("Creating " + className, 3);
    IPackageFragment aimPackage = src.getPackageFragment(packageName);
    String classContent = "package " + packageName + ";\n\n";
    classContent += "public class " + className + " {\n\n";
    classContent += "}";

    aimPackage.createCompilationUnit(className + ".java", classContent, false, null);
    monitor.worked(1);

    IPath templatePath = aimPackage.getPath();
    if (TapestryWizardUtils.isMavenProject(project)) {
        String javaPath = aimPackage.getPath().toString();
        String temPath = javaPath;
        if (javaPath.indexOf("/main/java/") > -1) {
            temPath = javaPath.replace("/main/java/", "/main/resources/");
        } else if (javaPath.indexOf("/test/java/") > -1) {
            temPath = javaPath.replace("/test/java/", "/test/resources/");
        }
        IPath tmpPath = new Path(temPath);
        if (tmpPath.isValidPath(temPath)) {
            templatePath = tmpPath;
        }
    }

    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IFile pageFile = root.getFile(templatePath.append(className + ".tml"));

    final IFile file = pageFile;
    try {
        InputStream stream = openContentStream();
        if (file.exists()) {
            file.setContents(stream, true, true, monitor);
        } else {
            file.create(stream, true, monitor);
        }
        stream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    monitor.worked(1);
    monitor.setTaskName("Opening file for editing...");
    getShell().getDisplay().asyncExec(new Runnable() {
        public void run() {
            IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
            try {
                IDE.openEditor(page, file, true);
            } catch (PartInitException e) {
            }
        }
    });
    monitor.worked(1);

}

From source file:org.bonitasoft.studio.common.repository.ClassGenerator.java

License:Open Source License

private static IType generateAbstractClass(String packageName, String className, String superClassName,
        SourceRepositoryStore sourceStore, IProgressMonitor progressMonitor) throws Exception {

    final IJavaProject javaProject = RepositoryManager.getInstance().getCurrentRepository().getJavaProject();

    NewClassWizardPage classWizard = new NewClassWizardPage();
    classWizard.setSuperClass(superClassName, false);
    classWizard.setAddComments(true, false);
    classWizard.setModifiers(classWizard.F_PUBLIC | classWizard.F_ABSTRACT, false);
    classWizard.setTypeName(className, false);
    classWizard.setMethodStubSelection(false, false, false, false);
    IPackageFragmentRoot packageFragmentRoot = null;
    IResource srcFolder = sourceStore.getResource();
    packageFragmentRoot = javaProject.getPackageFragmentRoot(srcFolder);
    classWizard.setPackageFragmentRoot(packageFragmentRoot, false);
    IPackageFragment packageFragment = packageFragmentRoot
            .getPackageFragment(packageName == null ? "" : packageName);
    if (!packageFragment.exists()) {
        packageFragment = packageFragmentRoot.createPackageFragment(packageName, true, progressMonitor);
    }//from   w w w  .j a  va 2 s .com
    classWizard.setPackageFragment(packageFragment, false);
    classWizard.createType(progressMonitor);
    return classWizard.getCreatedType();
}

From source file:org.bonitasoft.studio.common.repository.ClassGenerator.java

License:Open Source License

private static IType generateImplementationClass(String packageName, String className,
        SourceRepositoryStore sourceStore, IProgressMonitor progressMonitor) throws Exception {
    final IJavaProject javaProject = RepositoryManager.getInstance().getCurrentRepository().getJavaProject();

    IType abstractConnectorType = javaProject.findType(AbstractConnector.class.getName());
    IType abstractFilterType = javaProject.findType(AbstractUserFilter.class.getName());
    String abstractClassName = "Abstract" + className;
    if (packageName != null && !packageName.isEmpty()) {
        abstractClassName = packageName + "." + abstractClassName;
    }//from  w  ww .jav  a 2s .  c o  m
    IType classType = javaProject.findType(abstractClassName);
    if (classType == null) {
        throw new ClassNotFoundException(abstractClassName);
    }
    ITypeHierarchy hierarchy = classType.newTypeHierarchy(javaProject, progressMonitor);
    String tempatePattern = null;
    if (hierarchy.contains(abstractConnectorType)) {
        tempatePattern = "/**\n*The connector execution will follow the steps"
                + "\n* 1 - setInputParameters() --> the connector receives input parameters values"
                + "\n* 2 - validateInputParameters() --> the connector can validate input parameters values"
                + "\n* 3 - connect() --> the connector can establish a connection to a remote server (if necessary)"
                + "\n* 4 - executeBusinessLogic() --> execute the connector"
                + "\n* 5 - getOutputParameters() --> output are retrieved from connector"
                + "\n* 6 - disconnect() --> the connector can close connection to remote server (if any)\n*/";
    } else if (hierarchy.contains(abstractFilterType)) {
        tempatePattern = "/**\n*The actor filter execution will follow the steps"
                + "\n* 1 - setInputParameters() --> the actor filter receives input parameters values"
                + "\n* 2 - validateInputParameters() --> the actor filter can validate input parameters values"
                + "\n* 3 - filter(final String actorName) --> execute the user filter"
                + "\n* 4 - shouldAutoAssignTaskIfSingleResult() --> auto-assign the task if filter returns a single result\n*/";
    }

    NewClassWizardPage classWizard = new NewClassWizardPage();
    classWizard.enableCommentControl(true);

    ProjectTemplateStore fTemplateStore = new ProjectTemplateStore(
            RepositoryManager.getInstance().getCurrentRepository().getProject());
    try {
        fTemplateStore.load();
    } catch (IOException e) {
        BonitaStudioLog.error(e);
    }
    Template t = fTemplateStore.findTemplateById("org.eclipse.jdt.ui.text.codetemplates.typecomment");
    t.setPattern(tempatePattern);

    classWizard.setSuperClass(abstractClassName, false);
    classWizard.setAddComments(true, false);
    classWizard.setModifiers(classWizard.F_PUBLIC, false);
    classWizard.setTypeName(className, false);
    classWizard.setMethodStubSelection(false, false, false, false);
    IPackageFragmentRoot packageFragmentRoot = null;
    IResource srcFolder = sourceStore.getResource();
    packageFragmentRoot = javaProject.getPackageFragmentRoot(srcFolder);
    classWizard.setPackageFragmentRoot(packageFragmentRoot, false);
    IPackageFragment packageFragment = packageFragmentRoot
            .getPackageFragment(packageName == null ? "" : packageName);
    if (!packageFragment.exists()) {
        packageFragment = packageFragmentRoot.createPackageFragment(packageName, true, progressMonitor);
    }
    classWizard.setPackageFragment(packageFragment, false);
    classWizard.createType(progressMonitor);
    return classWizard.getCreatedType();
}

From source file:org.bonitasoft.studio.validators.ui.wizard.ValidatorWizard.java

License:Open Source License

/**
 * @param packageName//from  w w w .j a v a  2 s . co  m
 * @param className
 * @param baseClass
 * @param fields
 * @param progressMonitor
 * @return
 * @throws Exception
 */
private IType generateValidatorClass(String packageName, String className, Class<?> baseClass,
        IProgressMonitor progressMonitor) throws Exception {
    /*Use the NawClassWIzardPage to create the calss without pop up it*/
    NewClassWizardPage classWizard = new NewClassWizardPage();
    List<String> interfaces = new ArrayList<String>();
    progressMonitor.worked(1);
    interfaces.add(baseClass.getName());
    classWizard.setSuperInterfaces(interfaces, false);
    //   classWizard.setSuperClass(AbstractFormValidator.class.getName(), false);
    progressMonitor.worked(1);
    classWizard.setAddComments(true, false);
    classWizard.setModifiers(classWizard.F_PUBLIC, false);
    classWizard.setTypeName(className, false);
    classWizard.setMethodStubSelection(false, false, true, false);

    IResource srcFolder = validatorSourceStore.getResource();
    IJavaProject javaProject = (IJavaProject) srcFolder.getProject().getNature(JavaCore.NATURE_ID);
    IPackageFragmentRoot packageFragmentRoot = javaProject.getPackageFragmentRoot(srcFolder);
    classWizard.setPackageFragmentRoot(packageFragmentRoot, false);
    IPackageFragment packageFragment = packageFragmentRoot
            .getPackageFragment(packageName == null ? "" : packageName);
    if (!packageFragment.exists()) {
        packageFragment = packageFragmentRoot.createPackageFragment(packageName, true, progressMonitor);
    }
    classWizard.setPackageFragment(packageFragment, false);
    progressMonitor.worked(1);
    classWizard.createType(progressMonitor);

    IType classType = classWizard.getCreatedType();

    /*modify the generated class to implement the displayname method*/
    progressMonitor.worked(1);
    //      IMethod displayNameMethod = classType.getMethod("getDisplayName", new String[]{});
    //      if(displayNameMethod!=null && displayNameMethod.exists()){
    //         displayNameMethod.delete(true, progressMonitor);
    //      }
    //
    //      String contents = generateDisplayNameContent(displayName);
    //      classType.createMethod(contents, null, true, progressMonitor);

    return classType;
}

From source file:org.codehaus.groovy.eclipse.dsl.tests.BuiltInDSLInferencingTests.java

License:Open Source License

public void testSanity() throws Exception {
    IJavaProject javaProject = JavaCore.create(project);
    assertTrue("Should have DSL support classpath container",
            GroovyRuntime.hasClasspathContainer(javaProject, GroovyDSLCoreActivator.CLASSPATH_CONTAINER_ID));

    IClasspathContainer container = JavaCore
            .getClasspathContainer(GroovyDSLCoreActivator.CLASSPATH_CONTAINER_ID, javaProject);
    IClasspathEntry[] cpes = container.getClasspathEntries();
    assertEquals("Wrong number of classpath entries found: " + Arrays.toString(cpes), 2, cpes.length);

    IClasspathEntry pluginEntry = null;//from w ww  .ja va  2  s.com
    IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
    for (IClasspathEntry entry : entries) {
        if (entry.getPath().toString().contains("plugin_dsld")) {
            pluginEntry = entry;
        }
    }

    IPackageFragmentRoot root = null;
    List<String> elements = new ArrayList<String>();
    for (IJavaElement elt : javaProject.getChildren()) {
        elements.add(elt.getElementName());
        if (elt.getElementName().contains("plugin_dsld")) {
            root = (IPackageFragmentRoot) elt;
        }
    }

    List<String> possibleFrags = new ArrayList<String>();
    for (IPackageFragment frag : javaProject.getPackageFragments()) {
        if (frag.getElementName().equals("dsld")) {
            possibleFrags.add(frag.toString());
            possibleFrags.add("  [");
            for (IJavaElement child : frag.getChildren()) {
                possibleFrags.add("    " + child.getElementName());
            }
            possibleFrags.add("  ]");
        }
    }

    assertNotNull("Did not find the Plugin DSLD classpath entry.  Exsting resolved roots:\n"
            + printList(elements) + "\nOther DSLD fragments:\n" + printList(possibleFrags), pluginEntry);
    assertNotNull("Plugin DSLD classpath entry should exist.  Exsting resolved roots:\n" + printList(elements)
            + "\nOther DSLD fragments:\n" + printList(possibleFrags), root);
    assertTrue("Plugin DSLD classpath entry should exist", root.exists());

    ExternalPackageFragmentRoot ext = (ExternalPackageFragmentRoot) root;
    ext.resource().refreshLocal(IResource.DEPTH_INFINITE, null);
    root.close();
    root.open(null);

    IPackageFragment frag = root.getPackageFragment("dsld");
    assertTrue("DSLD package fragment should exist", frag.exists());
}

From source file:org.codehaus.groovy.eclipse.dsl.tests.DSLStoreTests.java

License:Open Source License

public void testDisabledOfJar() throws Exception {
    addJarToProject("simple_dsld.jar");
    env.fullBuild();/* w  w w.  ja v  a 2 s  .  co  m*/
    IPackageFragmentRoot root = JavaCore.create(project)
            .getPackageFragmentRoot(findExternalFilePath("simple_dsld.jar"));
    IStorage storage = (IStorage) root.getPackageFragment("dsld").getNonJavaResources()[0];

    assertDSLStore(1,
            createExpectedPointcuts(new IStorage[] { storage },
                    new String[] { createSemiUniqueName(CurrentTypePointcut.class, storage) }),

            createExpectedContributionCount(
                    new String[] { createSemiUniqueName(CurrentTypePointcut.class, storage) },
                    new Integer[] { 1 }));

    // disable script
    DSLPreferences.setDisabledScripts(new String[] { DSLDStore.toUniqueString(storage) });

    assertDSLStore(1, createExpectedPointcuts(new String[] {}),

            createExpectedContributionCount(new String[] {}, new Integer[] {}));

    // re-enable
    DSLPreferences.setDisabledScripts(new String[] {});

    assertDSLStore(1,
            createExpectedPointcuts(new IStorage[] { storage },
                    new String[] { createSemiUniqueName(CurrentTypePointcut.class, storage) }),

            createExpectedContributionCount(
                    new String[] { createSemiUniqueName(CurrentTypePointcut.class, storage) },
                    new Integer[] { 1 }));

    // remove from classpath
    removeJarFromProject("simple_dsld.jar");

    assertDSLStore(0, createExpectedPointcuts(new String[] {}),

            createExpectedContributionCount(new String[] {}, new Integer[] {}));

}

From source file:org.eclim.plugin.jdt.command.refactoring.MoveCommand.java

License:Open Source License

@Override
public Refactor createRefactoring(CommandLine commandLine) throws Exception {
    String project = commandLine.getValue(Options.PROJECT_OPTION);
    String file = commandLine.getValue(Options.FILE_OPTION);
    String packName = commandLine.getValue(Options.NAME_OPTION);

    ICompilationUnit src = JavaUtils.getCompilationUnit(project, file);
    IPackageFragmentRoot root = JavaModelUtil.getPackageFragmentRoot(src);
    IPackageFragment pack = root.getPackageFragment(packName);
    ICompilationUnit dest = pack.getCompilationUnit(src.getElementName());
    if (dest.exists()) {
        throw new RefactorException(
                Services.getMessage("move.element.exists", pack.getElementName(), src.getElementName()));
    }/*from   w w w.  j a  v a  2s.  com*/

    if (!pack.exists()) {
        pack = root.createPackageFragment(packName, true, null);
    }

    IMovePolicy policy = ReorgPolicyFactory.createMovePolicy(new IResource[0], new IJavaElement[] { src });

    JavaMoveProcessor processor = new JavaMoveProcessor(policy);
    IReorgDestination destination = ReorgDestinationFactory.createDestination(pack);
    RefactoringStatus status = processor.setDestination(destination);
    if (status.hasError()) {
        throw new RefactorException(status);
    }

    Shell shell = EclimPlugin.getShell();
    processor.setCreateTargetQueries(new CreateTargetQueries(shell));
    processor.setReorgQueries(new ReorgQueries(shell));

    Refactoring refactoring = new MoveRefactoring(processor);

    // create a more descriptive name than the default.
    String desc = refactoring.getName() + " (" + src.getElementName() + " -> " + pack.getElementName() + ')';

    return new Refactor(desc, refactoring);
}

From source file:org.eclipse.ajdt.core.javaelements.CompilationUnitTools.java

License:Open Source License

public static PackageFragment getParentPackage(IFile ajFile) {
    IJavaProject jp = JavaCore.create(ajFile.getProject());
    IJavaElement elem = JavaModelManager.determineIfOnClasspath(ajFile, jp);
    if (elem == null) {
        //not on classpath -> default package
        IPackageFragmentRoot root = jp.getPackageFragmentRoot(ajFile.getParent());
        elem = root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
    }/*  www  .j a v  a2  s . com*/
    if (elem instanceof PackageFragment) {
        return (PackageFragment) elem;
    }
    //should never happen

    return null;
}

From source file:org.eclipse.ajdt.internal.ui.wizards.NewTypeWizardPage.java

License:Open Source License

protected IStatus containerChanged() {
    IStatus status = super.containerChanged();
    IPackageFragmentRoot root = getPackageFragmentRoot();
    if ((fTypeKind == ANNOTATION_TYPE || fTypeKind == ENUM_TYPE) && !status.matches(IStatus.ERROR)) {
        if (root != null && !JavaModelUtil.is50OrHigher(root.getJavaProject())) {
            // error as createType will fail otherwise (bug 96928)
            return new StatusInfo(IStatus.ERROR,
                    Messages.format(NewWizardMessages.NewTypeWizardPage_warning_NotJDKCompliant,
                            BasicElementLabels.getJavaElementName(root.getJavaProject().getElementName())));
        }/*  w  w w. j a va 2s.  co m*/
        if (fTypeKind == ENUM_TYPE) {
            try {
                // if findType(...) == null then Enum is unavailable
                if (findType(root.getJavaProject(), "java.lang.Enum") == null) //$NON-NLS-1$
                    return new StatusInfo(IStatus.WARNING,
                            NewWizardMessages.NewTypeWizardPage_warning_EnumClassNotFound);
            } catch (JavaModelException e) {
                JavaPlugin.log(e);
            }
        }
    }

    fCurrPackageCompletionProcessor.setPackageFragmentRoot(root);
    if (root != null) {
        fEnclosingTypeCompletionProcessor.setPackageFragment(root.getPackageFragment("")); //$NON-NLS-1$
    }
    return status;
}

From source file:org.eclipse.ajdt.internal.ui.wizards.NewTypeWizardPage.java

License:Open Source License

/**
 * A hook method that gets called when the package field has changed. The method 
 * validates the package name and returns the status of the validation. The validation
 * also updates the package fragment model.
 * <p>/* w  w w.  ja  va  2s  .com*/
 * Subclasses may extend this method to perform their own validation.
 * </p>
 * 
 * @return the status of the validation
 */
protected IStatus packageChanged() {
    StatusInfo status = new StatusInfo();
    IPackageFragmentRoot root = getPackageFragmentRoot();
    fPackageDialogField.enableButton(root != null);

    IJavaProject project = root != null ? root.getJavaProject() : null;

    String packName = getPackageText();
    if (packName.length() > 0) {
        IStatus val = validatePackageName(packName, project);
        if (val.getSeverity() == IStatus.ERROR) {
            status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidPackageName,
                    val.getMessage()));
            return status;
        } else if (val.getSeverity() == IStatus.WARNING) {
            status.setWarning(Messages.format(
                    NewWizardMessages.NewTypeWizardPage_warning_DiscouragedPackageName, val.getMessage()));
            // continue
        }
    } else {
        status.setWarning(NewWizardMessages.NewTypeWizardPage_warning_DefaultPackageDiscouraged);
    }

    if (project != null) {
        if (project.exists() && packName.length() > 0) {
            try {
                IPath rootPath = root.getPath();
                IPath outputPath = project.getOutputLocation();
                if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) {
                    // if the bin folder is inside of our root, don't allow to name a package
                    // like the bin folder
                    IPath packagePath = rootPath.append(packName.replace('.', '/'));
                    if (outputPath.isPrefixOf(packagePath)) {
                        status.setError(NewWizardMessages.NewTypeWizardPage_error_ClashOutputLocation);
                        return status;
                    }
                }
            } catch (JavaModelException e) {
                JavaPlugin.log(e);
                // let pass         
            }
        }

        fCurrPackage = root.getPackageFragment(packName);
    } else {
        status.setError(""); //$NON-NLS-1$
    }
    return status;
}