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

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

Introduction

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

Prototype

String getElementName();

Source Link

Document

Returns the name of this element.

Usage

From source file:org.hibernate.eclipse.jdt.ui.wizards.NewHibernateMappingPreviewPage.java

License:Open Source License

/**
 * Try to create one change according with input file (fileSrc).
 * In case of success change be added into cc and returns true.
 * @param cc// w  w  w.  j  av  a 2 s. c  om
 * @param proj
 * @param fileSrc
 * @return
 */
protected boolean updateOneChange(final CompositeChange cc, final IJavaProject proj, File fileSrc) {
    boolean res = false;
    if (!fileSrc.exists()) {
        return res;
    }
    if (fileSrc.isDirectory()) {
        return res;
    }
    final IPath place2Gen = getRootPlace2Gen().append(proj.getElementName());
    final IPath filePathFrom = new Path(fileSrc.getPath());
    final IPath filePathTo_Proj = filePathFrom.makeRelativeTo(place2Gen);
    final IPath filePathTo_Show = proj.getPath().append(filePathTo_Proj);
    final IResource res2Update = proj.getProject().findMember(filePathTo_Proj);
    if (res2Update != null) {
        final ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
        ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(filePathTo_Show, LocationKind.IFILE);
        if (textFileBuffer == null) {
            try {
                bufferManager.connect(filePathTo_Show, LocationKind.IFILE, null);
                paths2Disconnect.add(filePathTo_Show);
            } catch (CoreException e) {
                HibernateConsolePlugin.getDefault().logErrorMessage("CoreException: ", e); //$NON-NLS-1$
            }
            textFileBuffer = bufferManager.getTextFileBuffer(filePathTo_Show, LocationKind.IFILE);
        }
        if (textFileBuffer != null) {
            IDocument documentChange = textFileBuffer.getDocument();
            //
            String str = readInto(fileSrc);
            TextEdit textEdit = new ReplaceEdit(0, documentChange.getLength(), str.toString());
            //
            TextFileChange change = new TextFileChange(filePathTo_Show.toString(), (IFile) res2Update);
            change.setSaveMode(TextFileChange.LEAVE_DIRTY);
            change.setEdit(textEdit);
            cc.add(change);
            //
            res = true;
        }
    } else {
        String str = readInto(fileSrc);
        CreateTextFileChange change = new CreateTextFileChange(filePathTo_Show, str.toString(), null,
                "hbm.xml"); //$NON-NLS-1$
        cc.add(change);
        //
        res = true;
    }
    return res;
}

From source file:org.j2eespider.util.ClassSearchUtil.java

License:Open Source License

/**
 * Return path of JavaSources defined in .classpath
 * @return/*  w w  w  .  j av a 2s . co m*/
 * @throws JavaModelException
 */
public static List<String> getJavaSources() throws JavaModelException {
    List<String> javaSources = new ArrayList<String>();

    IJavaProject javaProject = JavaCore.create(ConfigurationEditor.activeProject);
    IPackageFragmentRoot[] roots = javaProject.getAllPackageFragmentRoots();
    if (roots != null && roots.length > 0) {
        for (IPackageFragmentRoot root : roots) {
            if (root.getPath().segment(0).equals(javaProject.getElementName())) {
                javaSources.add(root.getPath().removeFirstSegments(1).makeRelative().toString());
            }
        }
    }

    return javaSources;
}

From source file:org.jboss.tools.arquillian.ui.internal.launcher.ArquillianLaunchConfigurationTab.java

License:Open Source License

private void handleSearchButtonSelected() {
    Shell shell = getShell();/*from   www  .  j ava 2s  .c  o  m*/

    IJavaProject javaProject = getJavaProject();

    IType[] types = new IType[0];
    boolean[] radioSetting = new boolean[2];
    try {
        // fix for 66922 Wrong radio behaviour when switching
        // remember the selected radio button
        radioSetting[0] = fTestRadioButton.getSelection();
        radioSetting[1] = fTestContainerRadioButton.getSelection();

        types = ArquillianSearchEngine.findTests(getLaunchConfigurationDialog(), javaProject,
                getSelectedTestKind());
    } catch (InterruptedException e) {
        setErrorMessage(e.getMessage());
        return;
    } catch (InvocationTargetException e) {
        JUnitPlugin.log(e.getTargetException());
        return;
    } finally {
        fTestRadioButton.setSelection(radioSetting[0]);
        fTestContainerRadioButton.setSelection(radioSetting[1]);
    }

    final HashSet<String> typeLookup = new HashSet<String>();
    for (IType type : types) {
        typeLookup.add(type.getPackageFragment().getElementName() + '/' + type.getTypeQualifiedName('.'));
    }
    SelectionDialog dialog = null;
    try {
        dialog = JavaUI.createTypeDialog(shell, getLaunchConfigurationDialog(),
                SearchEngine.createJavaSearchScope(new IJavaElement[] { javaProject },
                        IJavaSearchScope.SOURCES),
                IJavaElementSearchConstants.CONSIDER_ALL_TYPES, false, "**", //$NON-NLS-1$
                new TypeSelectionExtension() {
                    @Override
                    public ITypeInfoFilterExtension getFilterExtension() {
                        return new ITypeInfoFilterExtension() {
                            public boolean select(ITypeInfoRequestor requestor) {
                                StringBuffer buf = new StringBuffer();
                                buf.append(requestor.getPackageName()).append('/');
                                String enclosingName = requestor.getEnclosingName();
                                if (enclosingName.length() > 0)
                                    buf.append(enclosingName).append('.');
                                buf.append(requestor.getTypeName());
                                return typeLookup.contains(buf.toString());
                            }
                        };
                    }
                });
    } catch (JavaModelException e) {
        JUnitPlugin.log(e);
        return;
    }

    dialog.setTitle(JUnitMessages.JUnitLaunchConfigurationTab_testdialog_title);
    dialog.setMessage(JUnitMessages.JUnitLaunchConfigurationTab_testdialog_message);
    if (dialog.open() == Window.CANCEL) {
        return;
    }

    Object[] results = dialog.getResult();
    if ((results == null) || (results.length < 1)) {
        return;
    }
    IType type = (IType) results[0];

    if (type != null) {
        fTestText.setText(type.getFullyQualifiedName('.'));
        javaProject = type.getJavaProject();
        fProjText.setText(javaProject.getElementName());
    }
}

From source file:org.jboss.tools.arquillian.ui.internal.launcher.ArquillianLaunchConfigurationTab.java

License:Open Source License

private void handleProjectButtonSelected() {
    IJavaProject project = chooseJavaProject();
    if (project == null) {
        return;//www . j  av a2 s  . com
    }

    String projectName = project.getElementName();
    fProjText.setText(projectName);
}

From source file:org.jboss.tools.arquillian.ui.internal.launcher.ArquillianLaunchConfigurationTab.java

License:Open Source License

private Set<String> getMethodsForType(IJavaProject javaProject, IType type, TestKind testKind)
        throws JavaModelException {
    if (javaProject == null || type == null || testKind == null)
        return Collections.emptySet();

    String methodsCacheKey = javaProject.getElementName() + '\n' + type.getFullyQualifiedName() + '\n'
            + testKind.getId();//  w  ww  .j  ava  2s  .  c om
    if (methodsCacheKey.equals(fMethodsCacheKey))
        return fMethodsCache;

    Set<String> methodNames = new HashSet<String>();
    fMethodsCache = methodNames;
    fMethodsCacheKey = methodsCacheKey;

    boolean isJUnit4 = TestKindRegistry.JUNIT4_TEST_KIND_ID.equals(testKind.getId());

    while (type != null) {
        IMethod[] methods = type.getMethods();
        for (IMethod method : methods) {
            int flags = method.getFlags();
            // Only include public, non-static, no-arg methods that return void and start with "test":
            if (Modifier.isPublic(flags) && !Modifier.isStatic(flags) && method.getNumberOfParameters() == 0
                    && Signature.SIG_VOID.equals(method.getReturnType())
                    && method.getElementName().startsWith("test")) { //$NON-NLS-1$
                methodNames.add(method.getElementName());
            }
            if (isJUnit4) {
                IAnnotation annotation = method.getAnnotation("Test"); //$NON-NLS-1$
                if (annotation.exists()) {
                    methodNames.add(method.getElementName());
                }
            }
        }
        String superclassName = type.getSuperclassName();
        if (superclassName != null) {
            int pos = superclassName.indexOf('<');
            if (pos != -1)
                superclassName = superclassName.substring(0, pos);
            String[][] resolvedSupertype = type.resolveType(superclassName);
            if (resolvedSupertype != null && resolvedSupertype.length > 0) {
                String[] superclass = resolvedSupertype[0];
                type = javaProject.findType(superclass[0], superclass[1]);
            } else {
                type = null;
            }
        } else {
            type = null;
        }
    }
    return methodNames;
}

From source file:org.jboss.tools.common.jdt.debug.internal.RemoteDebugLaunchUtil.java

License:Open Source License

public static ILaunchConfiguration createOrGetDefaultLaunchConfiguration(String port, String host,
        IJavaProject javaProject, IJavaElement[] selection) throws CoreException {
    ILaunchConfiguration config = RemoteDebugActivator.getDefault().getDefaultLaunchConfiguration();
    ILaunchConfigurationWorkingCopy wc = null;
    if (config != null) {
        wc = config.getWorkingCopy();/*from  ww w  . j  ava 2 s .c om*/
        setAttribute(wc, host, port);
        wc.doSave();
    } else {
        ILaunchConfigurationType configType = getRemoteJavaApplicationConfigurationType();
        wc = createNewLaunchConfiguration(configType);
    }
    if (javaProject != null && javaProject.isOpen()) {
        wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, javaProject.getElementName());

        try {
            JavaMigrationDelegate.updateResourceMapping(wc);
        } catch (CoreException ce) {
            RemoteDebugActivator.pluginLog().logError(ce);
        }
    }
    setAttribute(wc, host, port);
    if (selection != null) {
        RemoteDebugActivator.configureSourceLookup(wc, selection, javaProject);
    }
    config = wc.doSave();
    return config;
}

From source file:org.jboss.tools.common.jdt.debug.internal.SourceLookupUtil.java

License:Open Source License

private ISourceLookupDirector addSourceContainers(ILaunchManager manager, ILaunchConfigurationWorkingCopy wc,
        IJavaElement[] selection, IJavaProject javaProject) throws CoreException {
    String memento = null;//  w  ww . j a v  a  2 s. co m
    String locatorId = null;
    try {
        memento = wc.getAttribute(ILaunchConfiguration.ATTR_SOURCE_LOCATOR_MEMENTO, (String) null);
        locatorId = wc.getAttribute(ILaunchConfiguration.ATTR_SOURCE_LOCATOR_ID, (String) null);
        if (locatorId == null) {
            locatorId = wc.getType().getSourceLocatorId();
        }
    } catch (CoreException e) {
        RemoteDebugActivator.pluginLog().logError(e);
    }
    IPersistableSourceLocator locator = manager.newSourceLocator(locatorId);
    if (memento != null) {
        locator.initializeFromMemento(memento);
    } else {
        locator.initializeDefaults(wc);
    }
    if (locator instanceof AbstractSourceLookupDirector) {
        ISourceLookupDirector director = (ISourceLookupDirector) locator;
        ArrayList<ISourceContainer> sourceContainers = new ArrayList<ISourceContainer>(
                Arrays.asList(director.getSourceContainers()));
        Set<String> projectNames = new LinkedHashSet<String>();
        if (javaProject != null) {
            projectNames.add(javaProject.getElementName());
        }
        for (int i = 0; i < selection.length; i++) {
            IJavaProject project = selection[i].getJavaProject();
            if (project instanceof IJavaProject && !project.equals(javaProject)) {
                projectNames.add(((IJavaProject) project).getElementName());
                sourceContainers.add(new JavaProjectSourceContainer((IJavaProject) project));
            }
        }

        director.setSourceContainers(
                (ISourceContainer[]) sourceContainers.toArray(new ISourceContainer[sourceContainers.size()]));
        director.setFindDuplicates(true);
        List<String> projectsList = new ArrayList<String>();
        projectsList.addAll(projectNames);
        wc.setAttribute(RemoteDebugActivator.ATTR_SELECTED_PROJECTS, projectsList);
        wc.setAttribute(ILaunchConfiguration.ATTR_SOURCE_LOCATOR_MEMENTO, director.getMemento());
        wc.setAttribute(ILaunchConfiguration.ATTR_SOURCE_LOCATOR_ID, director.getId());
        return director;
    } else {
        RemoteDebugActivator.pluginLog().logWarning("Launch configuration doesn't support source lookup");
    }
    return null;
}

From source file:org.jboss.tools.common.jdt.debug.ui.actions.LaunchDialogAction.java

License:Open Source License

public void run() {
    LaunchConfigurationManager lcManager = DebugUIPlugin.getDefault().getLaunchConfigurationManager();
    LaunchGroupExtension group = lcManager.getLaunchGroup(RemoteDebugActivator.LAUNCH_CATEGORY);
    LaunchConfigurationsDialog dialog = new LaunchConfigurationsDialog(getShell(), group);
    ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
    ILaunchConfigurationType type = manager
            .getLaunchConfigurationType(RemoteDebugActivator.REMOTE_JAVA_APPLICATION_ID);
    ILaunchConfiguration config = RemoteDebugActivator.getDefault().getDefaultLaunchConfiguration();
    ILaunchConfigurationWorkingCopy wc = null;
    try {/*from   w  w w . ja v a  2s  .c  om*/
        if (config == null) {
            wc = RemoteDebugActivator.createNewLaunchConfiguration(type);
        } else {
            wc = config.getWorkingCopy();
        }
    } catch (CoreException e) {
        RemoteDebugUIActivator.log(e);
        RemoteDebugUIActivator.displayLaunchError(getShell(), config, e);
    }
    IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
    ISelection currentSelection = page.getSelection();
    if (currentSelection instanceof ITreeSelection) {
        ITreeSelection selection = (ITreeSelection) currentSelection;
        Object object = selection.getFirstElement();
        if (!(object instanceof IJavaElement) && object instanceof IAdaptable) {
            object = ((IAdaptable) object).getAdapter(IJavaElement.class);
        }
        if (object instanceof IJavaElement) {
            IJavaElement javaElement = (IJavaElement) object;
            IJavaProject javaProject = javaElement.getJavaProject();
            if (javaProject != null) {
                try {
                    wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME,
                            javaProject.getElementName());
                    RemoteDebugUIActivator.getDefault().addSelectedProjects(wc, selection, javaProject);
                    config = wc.doSave();
                } catch (CoreException e) {
                    RemoteDebugUIActivator.log(e);
                    RemoteDebugUIActivator.displayLaunchError(getShell(), config, e);
                }
            }
        }
    }
    IStructuredSelection selection = new StructuredSelection(config);
    dialog.setInitialSelection(selection);
    dialog.setOpenMode(LaunchConfigurationsDialog.LAUNCH_CONFIGURATION_DIALOG_OPEN_ON_SELECTION);
    dialog.open();
}

From source file:org.jboss.tools.common.util.EclipseJavaUtil.java

License:Open Source License

/**
 * Returns IType found in a Java project by its qualified name.
 * The cache is used that is should be cleared explicitly by 
 * TypeResolutionCache.getInstance().clear();
 * Currently, it is done by KBBuilder so that this method works fine for all clients that 
 * request only projects with KB nature. Otherwise, non-existent object may be 
 * returned from the cache.//from w w w .j  av a 2  s . c o m
 * 
 * Now, it is not clear if the search over package roots, 
 * fulfilled when IJavaProject.findType(String) fails, makes sense.
 * There are neither tests nor use-cases that would support the need of it.
 * 
 * @param javaProject
 * @param qualifiedName
 * @return
 * @throws JavaModelException
 */
public static IType findType(IJavaProject javaProject, String qualifiedName) throws JavaModelException {
    if (qualifiedName == null || qualifiedName.length() == 0 || "void".equals(qualifiedName))
        return null;
    Map<String, IType> cache = typeCache.get(javaProject.getElementName());
    if (cache == null) {
        cache = new Hashtable<String, IType>();
        typeCache.put(javaProject.getElementName(), cache);
    } else {
        IType type = cache.get(qualifiedName);
        if (type != null) {
            if (type.exists()) {
                return type;
            } else {
                cache.remove(qualifiedName);
            }
        }
    }
    IType type = javaProject.findType(qualifiedName);
    if (type != null && type.exists()) {
        return register(cache, qualifiedName, type);
    }

    //TODO Either provide use-case that justifies the 
    //     direct search over roots when IJavaProject.findType(String) fails
    //     or remove this obsolete code.
    //      int dot = qualifiedName.lastIndexOf('.');
    //      String packageName = (dot < 0) ? "" : qualifiedName.substring(0, dot); //$NON-NLS-1$
    //      String shortName = qualifiedName.substring(dot + 1);
    //      IPackageFragmentRoot[] rs = javaProject.getPackageFragmentRoots();
    //      for (int i = 0; i < rs.length; i++) {
    //         IPackageFragment f = rs[i].getPackageFragment(packageName);
    //         if(f == null || !f.exists()) continue;
    //         ICompilationUnit[] us = f.getCompilationUnits();
    //         for (int j = 0; j < us.length; j++) {
    //            IType t = us[j].getType(shortName);
    //            if(t != null && t.exists()) return register(cache, qualifiedName, t);
    //         }
    //      }
    return null;
}

From source file:org.jboss.tools.gwt.core.GWTInstallFacetDelegate.java

License:Open Source License

private void createSample(final List<IPath> srcPaths, final IPath webContentPath,
        final IJavaProject javaProject, IProgressMonitor monitor) throws CoreException {

    if (srcPaths.size() <= 0) {
        LogHelper.logWarning(GWTCoreActivator.PLUGIN_ID, MessageFormat
                .format("No source folders were found in project {0}", javaProject.getElementName()));
        return;//w  w w  . j a v  a 2 s .  co  m
    }

    monitor.subTask("Creating sample code");

    javaProject.getProject().getWorkspace().run(new IWorkspaceRunnable() {
        public void run(IProgressMonitor monitor) throws CoreException {
            try {
                /**
                 * TODO: it is not secure to take the first source-folder
                 * that was found (there might be several of them).
                 */
                unzipSrc(srcPaths.get(0), javaProject);
                unzipWebContent(webContentPath, javaProject);
                copyGwtServlet(javaProject, webContentPath, monitor);

            } catch (IOException e) {
                throw new CoreException(
                        StatusUtils.getErrorStatus(GWTCoreActivator.PLUGIN_ID, "Could not unzip samples", e));
            }
        }
    }, monitor);

    javaProject.getProject().refreshLocal(IResource.DEPTH_INFINITE, monitor);
}