Example usage for org.eclipse.jdt.core IPackageFragment getJavaProject

List of usage examples for org.eclipse.jdt.core IPackageFragment getJavaProject

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IPackageFragment getJavaProject.

Prototype

IJavaProject getJavaProject();

Source Link

Document

Returns the Java project this element is contained in, or null if this element is not contained in any Java project (for instance, the IJavaModel is not contained in any Java project).

Usage

From source file:com.codenvy.ide.ext.java.server.internal.core.NameLookup.java

License:Open Source License

/**
 * Returns the first type in the given package whose name
 * matches the given (unqualified) name, or <code>null</code> if none
 * exist. Specifying a <code>null</code> package will result in no matches.
 * The domain of the search is bounded by the Java project from which
 * this name lookup was obtained./*w w  w.java  2s  .  c  om*/
 *
 * @param name
 *         the name of the type to find
 * @param pkg
 *         the package to search
 * @param partialMatch
 *         partial name matches qualify when <code>true</code>,
 *         only exact name matches qualify when <code>false</code>
 * @param acceptFlags
 *         a bit mask describing if classes, interfaces or both classes and interfaces
 *         are desired results. If no flags are specified, all types are returned.
 * @param considerSecondaryTypes
 *         flag to know whether secondary types has to be considered
 *         during the search
 * @see #ACCEPT_CLASSES
 * @see #ACCEPT_INTERFACES
 * @see #ACCEPT_ENUMS
 * @see #ACCEPT_ANNOTATIONS
 */
public IType findType(String name, IPackageFragment pkg, boolean partialMatch, int acceptFlags,
        boolean waitForIndices, boolean considerSecondaryTypes) {
    if (pkg == null)
        return null;

    SingleTypeRequestor typeRequestor = new SingleTypeRequestor();
    seekTypes(name, pkg, partialMatch, acceptFlags, typeRequestor, considerSecondaryTypes);
    IType type = typeRequestor.getType();

    if (type == null && considerSecondaryTypes) {
        type = findSecondaryType(pkg.getElementName(), name, pkg.getJavaProject(), waitForIndices, null);
    }
    return type;
}

From source file:com.google.gdt.eclipse.core.TypeCreator.java

License:Open Source License

public TypeCreator(IPackageFragment pckg, String simpleTypeName, ElementType elementType, String[] interfaces,
        boolean addComments) {
    this.pckg = pckg;
    this.simpleTypeName = simpleTypeName;
    this.elementType = elementType;
    this.interfaces = interfaces;
    this.addComments = addComments;
    this.lineDelimiter = StubUtility.getLineDelimiterUsed(pckg.getJavaProject());
}

From source file:com.google.gdt.eclipse.designer.model.widgets.panels.grid.FlexTableInfo.java

License:Open Source License

/**
 * Ensures that <code>FlexTableHelper</code> exists in given package.
 * /*  w w  w  . ja v  a2 s  .co m*/
 * @return the fully qualified name of <code>FlexTableHelper</code> in given package.
 */
public static String ensureFlexTableHelper(IPackageFragment packageFragment) throws Exception {
    String packageName = packageFragment.getElementName();
    String helperClassName = packageName + ".FlexTableHelper";
    if (packageFragment.getJavaProject().findType(helperClassName) == null) {
        String source = IOUtils2.readString(FlexTableInfo.class.getResourceAsStream("FlexTableHelper.jvt"));
        source = StringUtils.replace(source, "%packageName%", packageName);
        packageFragment.createCompilationUnit("FlexTableHelper.java", source, true, null);
        ProjectUtils.waitForAutoBuild();
    }
    return helperClassName;
}

From source file:com.google.gdt.eclipse.designer.util.type.ChooseBeanDialog.java

License:Open Source License

/**
 * Ask user choose type, accessible from given project and filtered using given contributors.
 *//* w  w  w.ja v  a 2  s. c  o  m*/
public static String chooseType(IPackageFragment packageFragment, IChooseBeanContributor[] contributors)
        throws JavaModelException {
    IJavaProject javaProject = packageFragment.getJavaProject();
    IJavaSearchScope searchScope = SearchEngine.createJavaSearchScope(new IJavaElement[] { javaProject });
    IRunnableContext context = DesignerPlugin.getActiveWorkbenchWindow();
    // prepare extension
    ChooseBeanTypeSelectionExtension extension = new ChooseBeanTypeSelectionExtension(packageFragment,
            searchScope, contributors);
    // prepare dialog dialog
    SelectionDialog dialog = JavaUI.createTypeDialog(DesignerPlugin.getShell(), context, searchScope,
            IJavaElementSearchConstants.CONSIDER_CLASSES, false, "", extension);
    dialog.setTitle("Choose a Widget");
    dialog.setMessage("Choose a GWT Widget (? = any character, * = any string)");
    // open and resutrn result
    if (dialog.open() == Window.OK) {
        IType type = (IType) dialog.getResult()[0];
        return type.getFullyQualifiedName();
    }
    // cancelled
    return null;
}

From source file:com.google.gdt.eclipse.designer.wizards.model.module.CreateEntryPointOperation.java

License:Open Source License

/**
 * Create EntryPoint./*from www.  j a  va  2 s . c o  m*/
 */
public IFile create(EntryPointConfiguration configuration) throws Exception {
    String className = configuration.getEntryPointName();
    String packageName = configuration.getPackageName();
    IPackageFragment packageFragment = getPackage(root, packageName);
    IFile file;
    if (Utils.supportMvp(packageFragment.getJavaProject()) && configuration.isUseMvp()) {
        // prepare variables
        Map<String, String> variables = configuration.getVariables();
        variables.put("className", className);
        // create files from MVP templates
        createMvpFactoryInterface(configuration);
        {
            // create View
            ViewConfiguration viewConfiguration = configuration.getViewConfiguration();
            CreateViewOperation viewOperation = new CreateViewOperation(root);
            viewOperation.create(viewConfiguration);
        }
        createMvpFactoryImplementation(configuration);
        createMvpMappers(configuration);
        // create EntryPoint
        file = createFileFromTemplate(packageFragment, className + ".java", "mvp/Module.java", variables);
    } else {
        // single java template
        file = super.create(configuration);
    }
    return file;
}

From source file:com.google.gdt.eclipse.designer.wizards.model.module.CreateModuleOperation.java

License:Open Source License

public IFile create(ModuleConfiguration configuration) throws Exception {
    String moduleName = configuration.getModuleName();
    String packageName = configuration.getPackageName();
    // create packages
    IPackageFragment packageFragment = getPackage(root, packageName);
    getPackage(root, packageName + ".client");
    getPackage(root, packageName + ".server");
    // //www .  j a v  a  2s.co m
    // create folders
    IJavaProject javaProject = packageFragment.getJavaProject();
    IProject project = javaProject.getProject();
    String webFolderName = WebUtils.getWebFolderName(project);
    IFolder webFolder = project.getFolder(webFolderName);
    IFolder webInfFolder = project.getFolder(webFolderName + "/WEB-INF");
    // create module
    IFile file;
    if (configuration.isCreateEntryPoint()) {
        // prepare variables
        Map<String, String> variables = configuration.getVariables();
        variables.put("packageName", packageName);
        variables.put("className", moduleName);
        // prepare 'bootstrap' variable
        String bootstrapPrefix = packageName + "." + moduleName;
        variables.put("bootstrap", bootstrapPrefix + "/" + bootstrapPrefix + ".nocache.js");
        // create module
        file = createFileFromTemplate(packageFragment, moduleName + ".gwt.xml", "Module.gwt.xml", variables);
        // create EntryPoint
        CreateEntryPointOperation entryPointOperation = new CreateEntryPointOperation(root);
        entryPointOperation.create(configuration.getEntryPointConfiguration());
        // create files from templates
        createFileFromTemplate(webFolder, moduleName + ".html", "Module.html", variables);
        createFileFromTemplate(webFolder, moduleName + ".css", "Module.css", variables);
        copyTemplateFiles(webFolder, "images");
        // configure web.xml
        if (!webInfFolder.getFile("web.xml").exists()) {
            variables.put("welcome-file-name", moduleName);
            createFileFromTemplate(webInfFolder, "web.xml", "web.xml", variables);
        }
        // open entry point in editor
        {
            String qualifiedEntryPoint = packageName + ".client." + moduleName;
            IType type = WorkspaceUtils.waitForType(root.getJavaProject(), qualifiedEntryPoint);
            IDE.openEditor(DesignerPlugin.getActivePage(), (IFile) type.getUnderlyingResource(),
                    IDesignerEditor.ID);
        }
    } else {
        // create empty module
        file = createFile(packageFragment, moduleName + ".gwt.xml",
                "<module>\r\n\t<inherits name=\"com.google.gwt.user.User\"/>\r\n</module>");
    }
    return file;
}

From source file:com.google.gdt.eclipse.designer.wizards.model.service.CreateServiceOperation.java

License:Open Source License

public void create(IPackageFragment packageFragment, String serviceName) throws Exception {
    // prepare packages names
    String servicePackageName = packageFragment.getElementName();
    String serverPackageName = getServerPackageName(packageFragment);
    // prepare variables
    Map<String, String> variables = new HashMap<String, String>();
    variables.put("servicePackage", servicePackageName);
    variables.put("serviceName", serviceName);
    // client//www. j  ava2  s.  c  om
    {
        // create RemoteService interface, "async" interface will be done by builder
        createFileFromTemplate(packageFragment, serviceName + ".java", "RemoteService.Service.java", variables);
        // open RemoteService in editor
        {
            String qualifiedServiceName = packageFragment.getElementName() + "." + serviceName;
            IType type = WorkspaceUtils.waitForType(packageFragment.getJavaProject(), qualifiedServiceName);
            JavaUI.openInEditor(type);
        }
    }
    // server: create implementation stub
    {
        // prepare server package
        IPackageFragment serverPackage;
        {
            IPackageFragmentRoot packageFragmentRoot = CodeUtils.getPackageFragmentRoot(packageFragment);
            serverPackage = packageFragmentRoot.createPackageFragment(serverPackageName, false, null);
        }
        // create implementation stub
        variables.put("serverPackage", serverPackageName);
        createFileFromTemplate(serverPackage, serviceName + "Impl.java", "RemoteService.ServiceImpl.java",
                variables);
    }
    // declare servlet
    addServlet_intoWebXML(packageFragment, serviceName, serverPackageName);
}

From source file:com.google.gdt.eclipse.designer.wizards.model.service.CreateServiceOperation.java

License:Open Source License

private void addServlet_intoWebXML(IPackageFragment packageFragment, String serviceName,
        String serverPackageName) throws CoreException, Exception {
    IProject project = packageFragment.getJavaProject().getProject();
    ModuleDescription moduleDescription = Utils.getSingleModule(packageFragment);
    ModuleElement module = Utils.readModule(moduleDescription);
    // update web.xml
    String webFolderName = WebUtils.getWebFolderName(project);
    IFile webFile = project.getFile(new Path(webFolderName + "/WEB-INF/web.xml"));
    WebDocumentEditContext context = new WebDocumentEditContext(webFile);
    try {//from ww w  .j  a v a  2  s . c om
        WebAppElement moduleElement = context.getWebAppElement();
        // add new servlet definition
        {
            String servletClassName = serverPackageName + "." + serviceName + "Impl";
            String pattern = "/" + module.getName() + "/" + serviceName;
            // servlet
            com.google.gdt.eclipse.designer.model.web.ServletElement servletElement = new com.google.gdt.eclipse.designer.model.web.ServletElement();
            moduleElement.addChild(servletElement);
            servletElement.setName(serviceName);
            servletElement.setClassName(servletClassName);
            // servlet-mapping
            com.google.gdt.eclipse.designer.model.web.ServletMappingElement servletMappingElement = new com.google.gdt.eclipse.designer.model.web.ServletMappingElement();
            moduleElement.addChild(servletMappingElement);
            servletMappingElement.setName(serviceName);
            servletMappingElement.setPattern(pattern);
        }
        // commit modifications
        context.commit();
    } finally {
        context.disconnect();
    }
}

From source file:com.google.gdt.eclipse.designer.wizards.model.service.ServiceComposite.java

License:Open Source License

@Override
protected String validate() {
    IPackageFragment packageFragment = m_clientPackageField.getPackageFragment();
    // validate package
    {//from w  w  w  .  java 2s.  com
        if (packageFragment == null) {
            return "Select client package.";
        }
        try {
            if (!Utils.isModuleSourcePackage(packageFragment)) {
                return "Package " + packageFragment.getElementName() + " is not a client package.";
            }
        } catch (Throwable e) {
            return "Exception: " + e.getMessage();
        }
    }
    // validate service name
    {
        String serviceName = m_serviceField.getText();
        if (serviceName.length() == 0) {
            return "Service name can not be empty.";
        }
        // check that service name is valid identifier
        IStatus status = JavaConventions.validateIdentifier(serviceName, null, null);
        if (status.getSeverity() == IStatus.ERROR) {
            return status.getMessage();
        }
        // check that there are no class with same name
        try {
            String qualifiedServiceName = packageFragment.getElementName() + "." + serviceName;
            if (packageFragment.getJavaProject().findType(qualifiedServiceName) != null) {
                return "Type with such name already exists.";
            }
        } catch (Throwable e) {
            DesignerPlugin.log(e);
        }
    }
    return null;
}

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

License:Open Source License

private void createType(IPackageFragment pckg, boolean addComments) throws CoreException {
    IJavaProject javaProject = pckg.getJavaProject();
    final IProgressMonitor monitor = new NullProgressMonitor();

    // Method name should already have been sanitized and validated, so all we
    // should have to do to get a type name is just capitalize it
    String simpleName = StringUtilities.capitalize(getMethodName());

    // See if the type name is already used
    String qualifiedName = JavaModelUtil.concatenateName(pckg.getElementName(), simpleName);
    IType existingType = JavaModelSearch.findType(javaProject, qualifiedName);
    if (existingType != null) {
        if (ClientBundleUtilities.isCssResource(javaProject, existingType)) {
            // If the existing type is a CssResource, we'll assume that it wraps
            // this CSS file and use it for our ClientBundle accessor return type
            // instead of trying to generate another CssResource here.
            customCssResourceType = existingType;
            return;
        } else {//from w  w  w . j ava 2 s. co  m
            // If it's not a CssResource, then we'll need to generate a CssResource
            // ourself, but we can't use the name. So, let's compute a similar name
            // that is not already in use.
            simpleName = StringUtilities.computeUniqueName(getExistingTopLevelTypeNames(pckg), simpleName);
        }
    }

    // Parse the CSS and see if there were problems
    CssParseResult result = parseCss();
    final IStatus status = result.getStatus();

    // Bail out when errors occur
    if (status.getSeverity() == IStatus.ERROR) {
        throw new CoreException(status);
    }

    // For warnings, just display them in a dialog (on the UI thread of course)
    // TODO: would nice if we could aggregate these and show them all at the end
    if (status.getSeverity() == IStatus.WARNING) {
        Display.getDefault().syncExec(new Runnable() {
            public void run() {
                MessageDialog.openWarning(null, "CSS Parsing", status.getMessage());
            }
        });
    }

    // Extract the CSS class names
    final Set<String> cssClassNames = ExtractClassNamesVisitor.exec(result.getStylesheet());

    TypeCreator gen = new TypeCreator(pckg, simpleName, TypeCreator.ElementType.INTERFACE,
            new String[] { ClientBundleUtilities.CSS_RESOURCE_TYPE_NAME }, addComments) {
        @Override
        protected void createTypeMembers(IType newType, ImportRewrite imports) throws CoreException {
            // Create an accessor method for each CSS class
            for (String cssClass : cssClassNames) {
                newType.createMethod(computeCssClassMethodSource(newType, cssClass), null, true, monitor);
            }
        }
    };
    customCssResourceType = gen.createType();
}