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

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

Introduction

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

Prototype

IResource getResource();

Source Link

Document

Returns the innermost resource enclosing this element.

Usage

From source file:org.hibernate.eclipse.console.utils.OpenMappingUtils.java

License:Open Source License

/**
 * Trying to find hibernate console config ejb3 mapping file,
 * which is corresponding to provided element.
 *   /*from w  ww  .  j a v a 2 s. c o  m*/
 * @param consoleConfig
 * @param element
 * @return
 */
@SuppressWarnings("unchecked")
public static IFile searchInEjb3MappingFiles(ConsoleConfiguration consoleConfig, Object element) {
    IFile file = null;
    if (consoleConfig == null) {
        return file;
    }
    final ConsoleConfiguration cc2 = consoleConfig;
    List<String> documentPaths = (List<String>) consoleConfig.execute(new ExecutionContext.Command() {
        public Object execute() {
            String persistenceUnitName = cc2.getPreferences().getPersistenceUnitName();
            EntityResolver entityResolver = cc2.getConfiguration().getEntityResolver();
            IService service = cc2.getHibernateExtension().getHibernateService();
            return service.getJPAMappingFilePaths(persistenceUnitName, entityResolver);
        }
    });
    if (documentPaths == null) {
        return file;
    }
    IJavaProject[] projs = ProjectUtils.findJavaProjects(consoleConfig);
    ArrayList<IPath> pathsSrc = new ArrayList<IPath>();
    ArrayList<IPath> pathsOut = new ArrayList<IPath>();
    ArrayList<IPath> pathsFull = new ArrayList<IPath>();
    for (int i = 0; i < projs.length; i++) {
        IJavaProject proj = projs[i];
        IPath projPathFull = proj.getResource().getLocation();
        IPath projPath = proj.getPath();
        IPath projPathOut = null;
        try {
            projPathOut = proj.getOutputLocation();
            projPathOut = projPathOut.makeRelativeTo(projPath);
        } catch (JavaModelException e) {
            // just ignore
        }
        IPackageFragmentRoot[] pfrs = new IPackageFragmentRoot[0];
        try {
            pfrs = proj.getAllPackageFragmentRoots();
        } catch (JavaModelException e) {
            // just ignore
        }
        for (int j = 0; j < pfrs.length; j++) {
            // TODO: think about possibility to open resources from jar files
            if (pfrs[j].isArchive() || pfrs[j].isExternal()) {
                continue;
            }
            final IPath pathSrc = pfrs[j].getPath();
            final IPath pathOut = projPathOut;
            final IPath pathFull = projPathFull;
            pathsSrc.add(pathSrc);
            pathsOut.add(pathOut);
            pathsFull.add(pathFull);
        }
    }
    int scanSize = Math.min(pathsSrc.size(), pathsOut.size());
    scanSize = Math.min(pathsFull.size(), scanSize);
    for (int i = 0; i < scanSize && file == null; i++) {
        final IPath pathSrc = pathsSrc.get(i);
        final IPath pathOut = pathsOut.get(i);
        final IPath pathFull = pathsFull.get(i);
        Iterator<String> it = documentPaths.iterator();
        while (it.hasNext() && file == null) {
            String docPath = it.next();
            IPath path2DocFull = Path.fromOSString(docPath);
            IPath resPath = path2DocFull.makeRelativeTo(pathFull);
            if (pathOut != null) {
                resPath = resPath.makeRelativeTo(pathOut);
            }
            resPath = pathSrc.append(resPath);
            file = ResourcesPlugin.getWorkspace().getRoot().getFile(resPath);
            if (file == null || !file.exists()) {
                file = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(resPath);
            }
            if (file != null && file.exists()) {
                if (elementInFile(consoleConfig, file, element)) {
                    break;
                }
            }
            file = null;
        }
    }
    return file;
}

From source file:org.hibernate.eclipse.console.utils.ProjectUtils.java

License:Open Source License

private static String[] projectPersistenceUnits(IJavaProject javaProject) {
    if (javaProject == null || javaProject.getResource() == null) {
        return new String[0];
    }/*from  ww w.  j a  v  a  2  s. c  o m*/
    IPath projPathFull = javaProject.getResource().getLocation();
    IPath projPath = javaProject.getPath();
    IPath path = javaProject.readOutputLocation().append("META-INF/persistence.xml"); //$NON-NLS-1$
    path = path.makeRelativeTo(projPath);
    path = projPathFull.append(path);
    IFile file = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path);
    if (!exists(file)) {
        return new String[0];
    }
    InputStream is = null;
    org.dom4j.Document doc = null;
    try {
        is = file.getContents();
        SAXReader saxReader = new SAXReader();
        doc = saxReader.read(new InputSource(is));
    } catch (CoreException e) {
        HibernateConsolePlugin.getDefault().logErrorMessage("CoreException: ", e); //$NON-NLS-1$
    } catch (DocumentException e) {
        HibernateConsolePlugin.getDefault().logErrorMessage("DocumentException: ", e); //$NON-NLS-1$
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (IOException ioe) {
            //ignore
        }
    }
    if (doc == null || doc.getRootElement() == null) {
        return new String[0];
    }
    Iterator<?> it = doc.getRootElement().elements("persistence-unit").iterator(); //$NON-NLS-1$
    ArrayList<String> res = new ArrayList<String>();
    while (it.hasNext()) {
        Element el = (Element) it.next();
        res.add(el.attributeValue("name")); //$NON-NLS-1$
    }
    return res.toArray(new String[0]);
}

From source file:org.jboss.tools.fuse.transformation.editor.internal.util.Util.java

License:Open Source License

public static void ensureSourceFolderExists(IJavaProject javaProject, String folderName,
        IProgressMonitor monitor) throws Exception {
    boolean exists = false;
    IClasspathEntry[] entries = javaProject.getRawClasspath();
    IPath path = javaProject.getPath().append(folderName);
    for (IClasspathEntry entry : entries) {
        if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE && entry.getPath().equals(path)) {
            exists = true;/*w  w  w  .j  a v  a 2s  .  co m*/
            File folder = javaProject.getResource().getLocation().append(folderName).toFile();
            if (!folder.exists()) {
                if (!folder.mkdirs()) {
                    throw new Exception(Messages.bind(Messages.Util_UnableToCreateSourceFolder, folder));
                }
                javaProject.getProject().refreshLocal(IResource.DEPTH_INFINITE, monitor);
            }
            break;
        }
    }
    if (!exists) {
        IClasspathEntry[] newEntries = Arrays.copyOf(entries, entries.length + 1);
        newEntries[entries.length] = JavaCore.newSourceEntry(path);
        javaProject.setRawClasspath(newEntries, monitor);
        javaProject.save(monitor, true);
    }
}

From source file:org.jboss.tools.seam.ui.wizard.SelectJavaPackageAction.java

License:Open Source License

@Override
public void run() {
    String projectName = (String) getFieldEditor().getData(ISeamParameter.SEAM_PROJECT_NAME);
    if (projectName == null) {
        return;/*  w w w  .  j a v a 2  s.  c  om*/
    }
    IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
    if (project == null) {
        SeamGuiPlugin.getPluginLog().logError("Can't find java project with name: " + projectName);
        return;
    }
    SeamProjectsSet seamPrjSet = new SeamProjectsSet(project);
    IProject ejbProject = seamPrjSet.getEjbProject();
    if (ejbProject != null) {
        project = ejbProject;
    }
    IJavaProject javaProject = EclipseResourceUtil.getJavaProject(project);
    if (javaProject == null) {
        SeamGuiPlugin.getPluginLog().logError("Can't find java project with name: " + projectName);
        return;
    }
    IPackageFragmentRoot packageFragmentRoot = null;
    IPackageFragmentRoot[] roots;
    try {
        roots = javaProject.getPackageFragmentRoots();
        for (int i = 0; i < roots.length; i++) {
            if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
                packageFragmentRoot = roots[i];
                break;
            }
        }
    } catch (JavaModelException e) {
        SeamGuiPlugin.getPluginLog().logError(e);
    }
    if (packageFragmentRoot == null) {
        packageFragmentRoot = javaProject.getPackageFragmentRoot(javaProject.getResource());
    }
    if (packageFragmentRoot == null) {
        SeamGuiPlugin.getPluginLog().logError("Can't find src folder for project " + projectName);
        return;
    }
    IJavaElement[] packages = null;
    try {
        packages = packageFragmentRoot.getChildren();
    } catch (JavaModelException e) {
        SeamGuiPlugin.getPluginLog().logError(e);
    }
    if (packages == null) {
        packages = new IJavaElement[0];
    }

    String initialValue = getFieldEditor().getValue().toString();
    IJavaElement initialElement = null;
    ArrayList<IJavaElement> packagesWithoutDefaultPackage = new ArrayList<IJavaElement>();
    for (IJavaElement packageElement : packages) {
        String packageName = packageElement.getElementName();
        if (packageName.length() > 0) {
            packagesWithoutDefaultPackage.add(packageElement);
            if (packageName.equals(initialValue)) {
                initialElement = packageElement;
            }
        }
    }

    packages = packagesWithoutDefaultPackage.toArray(new IJavaElement[packagesWithoutDefaultPackage.size()]);
    ElementListSelectionDialog dialog = new ElementListSelectionDialog(Display.getCurrent().getActiveShell(),
            new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT));
    dialog.setTitle(J2EEUIMessages.PACKAGE_SELECTION_DIALOG_TITLE);
    dialog.setMessage(J2EEUIMessages.PACKAGE_SELECTION_DIALOG_DESC);
    dialog.setEmptyListMessage(J2EEUIMessages.PACKAGE_SELECTION_DIALOG_MSG_NONE);
    dialog.setElements(packages);
    if (initialElement != null) {
        dialog.setInitialSelections(new Object[] { initialElement });
    }
    if (dialog.open() == Window.OK) {
        IPackageFragment fragment = (IPackageFragment) dialog.getFirstResult();
        if (fragment != null) {
            getFieldEditor().setValue(fragment.getElementName());
        } else {
            getFieldEditor().setValue("");
        }
    }
}

From source file:org.key_project.key4eclipse.starter.core.test.testcase.KeYUtilTest.java

License:Open Source License

/**
 * Tests {@link KeYUtil#getProgramMethod(IMethod, de.uka.ilkd.key.java.JavaInfo)}
 *//*from w ww. ja va  2 s . c  o  m*/
@Test
public void testGetProgramMethod() throws Exception {
    // Create test project and content
    IJavaProject project = TestUtilsUtil.createJavaProject("KeYUtilTest_testGetProgramMethod");
    IFolder src = project.getProject().getFolder("src");
    BundleUtil.extractFromBundleToWorkspace(Activator.PLUGIN_ID, "data/jdtMethodToKeYProgramMethodTest", src);
    TestUtilsUtil.waitForBuild();
    // Get JDT method
    IType type = project.findType("JDTMethodToKeYProgramMethodTest");
    IMethod doSomething = type.getMethods()[0];
    assertEquals("doSomething", doSomething.getElementName());
    IType innerType = type.getType("InnerClass");
    assertNotNull(innerType);
    IMethod run = innerType.getMethods()[0];
    assertEquals("run", run.getElementName());
    // Open project in KeY
    KeYEnvironment<?> environment = KeYEnvironment.load(ResourceUtil.getLocation(project.getResource()), null,
            null);
    try {
        JavaInfo javaInfo = environment.getJavaInfo();
        // Test conversion of doSomething
        IProgramMethod pm = KeYUtil.getProgramMethod(doSomething, javaInfo);
        assertNotNull(pm);
        assertEquals("doSomething", pm.getFullName());
        assertEquals("JDTMethodToKeYProgramMethodTest", pm.getContainerType().getFullName());
        // Test conversion of run
        pm = KeYUtil.getProgramMethod(run, javaInfo);
        assertNotNull(pm);
        assertEquals("run", pm.getFullName());
        assertEquals("JDTMethodToKeYProgramMethodTest.InnerClass", pm.getContainerType().getFullName());
    } finally {
        environment.dispose();
    }
}

From source file:org.limy.eclipse.qalab.action.ViewReportAction.java

License:Open Source License

@Override
protected void doAction(IJavaElement javaElement, IProgressMonitor monitor) throws CoreException {

    IJavaProject project = javaElement.getJavaProject();
    LimyQalabEnvironment env = LimyQalabPluginUtils.createEnv(project.getProject());
    IPreferenceStore store = env.getStore();

    String destDir = store.getString(LimyQalabConstants.KEY_DEST_DIR);

    IPath projectRootPath = project.getResource().getLocation();
    IPath targetFile = projectRootPath.append(destDir).append("qalab/index.html");
    try {/*from   w ww. j  a va 2s.c  om*/
        LimyUIUtils.openBrowser(targetFile.toFile().toURI().toURL());
    } catch (MalformedURLException e) {
        LimyEclipsePluginUtils.log(e);
    }

}

From source file:org.mobicents.eclipslee.servicecreation.wizards.generic.FilenamePage.java

License:Apache License

/**
 * Tests if the current workbench selection is a suitable
 * container to use.//from   w ww.j a v a2  s .c  o  m
 */

private void initialize() {
    if (selection != null && selection.isEmpty() == false && selection instanceof IStructuredSelection) {

        IJavaElement element = getInitialJavaElement((IStructuredSelection) selection);
        IPackageFragmentRoot initialRoot;
        initialRoot = JavaModelUtil.getPackageFragmentRoot(element);
        if (initialRoot == null || initialRoot.isArchive()) {
            IJavaProject javaProject = element.getJavaProject();
            if (javaProject != null) {
                try {
                    initialRoot = null;
                    if (javaProject.exists()) {
                        IPackageFragmentRoot roots[] = javaProject.getPackageFragmentRoots();
                        for (int i = 0; i < roots.length; i++) {
                            if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
                                initialRoot = roots[i];
                                break;
                            }
                        }
                    }
                } catch (JavaModelException e) {
                    ServiceCreationPlugin.log("JavaModelException determining project root.");
                }
                if (initialRoot == null) {
                    initialRoot = javaProject.getPackageFragmentRoot(javaProject.getResource());
                }
            }
        }

        try {
            setSourceContainer((IFolder) initialRoot.getCorrespondingResource());
        } catch (JavaModelException e) {
            ServiceCreationPlugin.log("JavaModelException thrown setting source container on FilenamePage");
        }

        //         // Initialize the maven module dialog
        //         mavenModuleText.setText(mavenModule);

        // Initialize the filename dialog
        fileText.setText("__Replace_Me__" + ends);

        if (element != null && element.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
            IPackageFragment fragment = (IPackageFragment) element;
            setPackage(fragment);
            return;
        }

        if (element != null && element.getElementType() == IJavaElement.COMPILATION_UNIT) {
            ICompilationUnit unit = (ICompilationUnit) element;
            IPackageFragment fragment = (IPackageFragment) unit.getParent();
            setPackage(fragment);
            return;
        }

        setPackage(null);
    }

}

From source file:org.springframework.ide.eclipse.data.jdt.core.SpringDataCompilationParticipant.java

License:Open Source License

@Override
public boolean isActive(IJavaProject project) {
    return SpringCoreUtils.isSpringProject(project.getResource());
}

From source file:org.switchyard.tools.ui.editor.components.camel.sftp.CamelSFTPConsumerComposite.java

License:Open Source License

private void browse() {
    final String pathString = _privateKeyFileText.getText();
    IResource resource = null;/* w  ww  .j  a  v a  2  s. c o  m*/
    IProject resProject = SwitchyardSCAEditor.getActiveEditor().getModelFile().getProject();
    IJavaProject javaProject = JavaCore.create(resProject);
    if (pathString == null || pathString.isEmpty()) {
        final IResource temp = JavaUtil.getFirstResourceRoot(javaProject);
        resource = temp == null ? javaProject.getResource() : temp;
    } else {
        final IPath path = new Path(pathString);
        if (path.isValidPath(pathString)) {
            try {
                resource = javaProject.getProject().getWorkspace().getRoot().getFile(path);
            } catch (IllegalArgumentException e) {
                final IResource temp = JavaUtil.getFirstResourceRoot(javaProject);
                resource = temp == null ? javaProject.getResource() : temp;
            }
        } else {
            final IResource temp = JavaUtil.getFirstResourceRoot(javaProject);
            resource = temp == null ? javaProject.getResource() : temp;
        }
    }

    if (resource != null) {
        ClasspathResourceSelectionDialog dialog = new ClasspathResourceSelectionDialog(getPanel().getShell(),
                resource.getProject());
        dialog.setInitialPattern("*.*");
        dialog.setTitle("Select Private Key File");
        if (dialog.open() == ClasspathResourceSelectionDialog.OK) {
            _privateKeyFileText.setText(((IResource) dialog.getFirstResult()).getFullPath().toString());
            handleModify(_privateKeyFileText);
        }
    }
}

From source file:org.switchyard.tools.ui.editor.components.camel.sftp.CamelSFTPSecurityComposite.java

License:Open Source License

private void browse() {
    final String pathString = _privateKeyFileText.getText();
    IResource resource = null;/*from   w w w. ja v a 2 s.co  m*/
    IProject resProject = SwitchyardSCAEditor.getActiveEditor().getModelFile().getProject();
    IJavaProject javaProject = JavaCore.create(resProject);
    if (pathString == null || pathString.isEmpty()) {
        final IResource temp = JavaUtil.getFirstResourceRoot(javaProject);
        resource = temp == null ? javaProject.getResource() : temp;
    } else {
        final IPath path = new Path(pathString);
        if (path.isValidPath(pathString)) {
            try {
                resource = javaProject.getProject().getWorkspace().getRoot().getFile(path);
            } catch (IllegalArgumentException e) {
                final IResource temp = JavaUtil.getFirstResourceRoot(javaProject);
                resource = temp == null ? javaProject.getResource() : temp;
            }
        } else {
            final IResource temp = JavaUtil.getFirstResourceRoot(javaProject);
            resource = temp == null ? javaProject.getResource() : temp;
        }
    }

    if (resource != null) {
        ClasspathResourceSelectionDialog dialog = new ClasspathResourceSelectionDialog(getPanel().getShell(),
                resource.getProject());
        dialog.setInitialPattern("*.*"); //$NON-NLS-1$
        dialog.setTitle(Messages.title_selectPrivateKeyFile);
        if (dialog.open() == ClasspathResourceSelectionDialog.OK) {
            _privateKeyFileText.setText(((IResource) dialog.getFirstResult()).getFullPath().toString());
            // make sure a notify event gets sent, to update the binding
            _privateKeyFileText.notifyListeners(SWT.Modify, null);
            // simulate "ENTER" to commit the change
            _privateKeyFileText.notifyListeners(SWT.DefaultSelection, null);
            _privateKeyFileText.setFocus();
        }
    }
}