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:com.technophobia.substeps.syntax.ProjectToSyntaxTransformer.java

License:Open Source License

private IPath projectLocationPath(final IJavaProject project) {
    return project.getResource().getLocation().makeAbsolute();
}

From source file:com.windowtester.eclipse.ui.convert.WTAPIUsage.java

License:Open Source License

private void collectPluginsReferencedInManifest(Collection<String> pluginIds, IJavaProject proj)
        throws IOException {
    IPath location = proj.getResource().getLocation();
    if (location != null) {
        File pluginXmlFile = null;
        for (File dir : location.toFile().listFiles()) {
            if (!dir.isDirectory() || !dir.getName().equalsIgnoreCase("META-INF"))
                continue;
            for (File file : dir.listFiles()) {
                String name = file.getName();
                if (!name.equalsIgnoreCase("MANIFEST.MF")) {
                    if (name.equalsIgnoreCase("plugin.xml"))
                        pluginXmlFile = file;
                    continue;
                }//from w w  w.j  av a 2 s  .co m
                BundleManifestReader reader = new BundleManifestReader();
                reader.process(file);
                for (String id : reader.getRequiredPlugins()) {
                    if (id.startsWith("com.windowtester."))
                        pluginIds.add(id);
                }
                return;
            }
        }
        if (pluginXmlFile != null)
            pluginIds.add("unknown plugins referenced in " + proj.getResource().getName() + "/"
                    + pluginXmlFile.getName());
    }
}

From source file:fede.workspace.dependencies.eclipse.java.ItemDependenciesClasspathResolver.java

License:Apache License

@Override
public void initialize(IPath containerPath, IJavaProject project) throws CoreException {

    /*//w ww. java 2 s  .com
     * Verify if the project is associated with an item, otherwise left it
     * unbounded
     */
    Item item = null;
    try {
        item = WSPlugin.sGetItemFromResource(project.getResource());
    } catch (Throwable e) {
    }
    UUID id = null;
    if (item == null) {
        try {
            id = MelusineProjectManager.getUUIDItem(project.getResource());
        } catch (Throwable e) { // ignored
        }
    }
    IClasspathContainer previousSessionContainer = JavaCore.getClasspathContainer(containerPath, project);

    IClasspathContainer container = new ItemDependenciesClasspathEntry(project, project.getElementName(), item,
            id, previousSessionContainer);

    JavaCore.setClasspathContainer(containerPath, new IJavaProject[] { project },
            new IClasspathContainer[] { container }, null);
}

From source file:fede.workspace.eclipse.composition.java.ItemComponentsClasspathResolverClasses.java

License:Apache License

@Override
public void initialize(IPath containerPath, IJavaProject javaProject) throws CoreException {
    /*/*from   www. j av a  2 s.co  m*/
     * Verify if the project is associated with an item, otherwise left it
     * unbounded
     */
    Item item = WSPlugin.sGetItemFromResource(javaProject.getResource());
    if (item == null) {
        return;
    }

    IClasspathContainer container = new ItemComponentsClasspathEntryClasses(javaProject, item, true);
    JavaCore.setClasspathContainer(containerPath, new IJavaProject[] { javaProject },
            new IClasspathContainer[] { container }, null);
}

From source file:firststep.plugin.wizard.FirstStepProjectCreationWizard.java

License:Open Source License

@Override
public boolean performFinish() {
    WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
        @Override//from  w ww  .  ja  v a  2  s.  c om
        protected void execute(IProgressMonitor monitor)
                throws CoreException, InvocationTargetException, InterruptedException {
            fJavaPage.performFinish(monitor);
            // use the result from the extra page

        }
    };
    try {
        getContainer().run(false, true, op);

        IJavaProject newElement = fJavaPage.getJavaProject();

        IWorkingSet[] workingSets = fMainPage.getWorkingSets();
        if (workingSets.length > 0) {
            PlatformUI.getWorkbench().getWorkingSetManager().addToWorkingSets(newElement, workingSets);
        }
        BasicNewProjectResourceWizard.updatePerspective(fConfigElement);
        BasicNewResourceWizard.selectAndReveal(newElement.getResource(),
                PlatformUI.getWorkbench().getActiveWorkbenchWindow());

    } catch (InvocationTargetException e) {
        return false; // TODO: should open error dialog and log
    } catch (InterruptedException e) {
        return false; // canceled
    }
    return true;
}

From source file:net.harawata.mybatipse.mybatis.ConfigRegistry.java

License:Open Source License

/**
 * Scans the project and returns the MyBatis config file if found.<br>
 * If there are multiple files in the project, only the first one is returned.
 * //ww  w.  j  a v  a 2s.  c o  m
 * @param project
 * @return MyBatis config file or <code>null</code> if none found.
 */
private Map<IFile, IContentType> search(IJavaProject project) {
    final Map<IFile, IContentType> configFiles = new ConcurrentHashMap<IFile, IContentType>();
    try {
        project.getResource().accept(new ConfigVisitor(configFiles), IContainer.NONE);

        for (IPackageFragmentRoot root : project.getPackageFragmentRoots()) {
            if (root.getKind() != IPackageFragmentRoot.K_SOURCE)
                continue;
            root.getResource().accept(new ConfigVisitor(configFiles), IContainer.NONE);
        }
    } catch (CoreException e) {
        Activator.log(Status.ERROR, "Searching MyBatis Config xml failed.", e);
    }

    return configFiles;
}

From source file:net.sf.jasperreports.eclipse.classpath.JavaProjectClassLoader.java

License:Open Source License

protected void init(IJavaProject project) {
    if (project == null || !project.exists() || !project.getResource().isAccessible())
        throw new IllegalArgumentException("Invalid javaProject");
    this.javaProject = project;
    getURLClassloader();/*w w  w.j a  va2s  .co m*/
    listener = new IElementChangedListener() {

        public void elementChanged(final ElementChangedEvent event) {
            if (ignoreClasspathChanges(event))
                return;
            System.out.println("CLASSPATH CHANGED:" + event);
            // FIXME should release this classloader
            // what happend with current objects? we have 1 loader per
            // project, maybe se can filter some events? to have less
            // updates
            curlLoader = null;
            getURLClassloader();
            if (events != null)
                events.firePropertyChange("classpath", false, true);
        }
    };
    JavaCore.addElementChangedListener(listener, ElementChangedEvent.POST_CHANGE);
}

From source file:net.sourceforge.eclipsejetty.launch.JettyLaunchConfigurationDelegate.java

License:Apache License

public String getCatalinaHomeForProject(ILaunchConfiguration configuration) throws CoreException {

    // calculate "catalina.base" dir to be located under $project_root/target/catalina.base
    IJavaProject project = getJavaProject(configuration);
    String projectRoot = project.getResource().getLocation().toString();

    //  outputDir should be equal to "target/classes", then remove "classes" folder

    String catalinaBase = projectRoot + File.separator + "target" + File.separator + "catalina.base";

    File cbase = new File(catalinaBase);
    if (cbase.exists()) {
        cbase.delete();/*  w  ww .j ava2 s. com*/
    }
    if (!cbase.exists()) {
        cbase.mkdirs();
    }

    return catalinaBase;
}

From source file:net.sourceforge.eclipsejetty.launch.JettyLaunchConfigurationDelegate.java

License:Apache License

private File createTomcatConfigurationFile(ILaunchConfiguration configuration, ContainerVersion version,
        String catalinaBase, String[] classpath) throws CoreException {

    AbstractServerConfiguration serverConfiguration = version.createServerConfiguration();

    // the file name is the name of the context
    String contextPath = JettyPluginConstants.getContext(configuration);
    if (contextPath != null && !contextPath.trim().equals("")) {
        if (contextPath.trim().equals("/") || contextPath.trim().toLowerCase().equals("/root")
                || contextPath.trim().toLowerCase().equals("root")) {
            contextPath = "ROOT";
        }/*  w  w w .j a  va  2s .  co m*/

        if (contextPath.startsWith("/")) {
            contextPath = contextPath.substring(1);
        }

    } else {
        contextPath = "ROOT";
    }

    File file = new File(catalinaBase, "conf/Catalina/localhost/" + contextPath + ".xml");

    // if the file exists, rewrite it
    if (file.exists()) {
        file.delete();
    }
    // check if the parent dirs exist
    File parentDirs = file.getParentFile();
    if (!parentDirs.exists()) {
        parentDirs.mkdirs();
    }

    // get absolute path for webapp folder.
    IJavaProject project = getJavaProject(configuration);
    String projectname = getResourceUri(project.getResource());
    String projectRoot = project.getResource().getLocation().toString();
    File webappdir = new File(projectRoot, JettyPluginConstants.getWebAppDir(configuration));

    String outputFolder = project.getOutputLocation().makeAbsolute().toString();
    String outputDir = null;
    if (outputFolder.startsWith(projectname)) {
        outputDir = outputFolder.substring(projectname.length());
    } else {
        outputDir = outputFolder;
    }

    String absOutDir = projectRoot + outputDir;

    serverConfiguration.setDefaultContextPath(JettyPluginConstants.getContext(configuration));
    serverConfiguration.setDefaultWar(webappdir.getAbsolutePath());
    serverConfiguration.addDefaultClasspath(classpath);
    serverConfiguration.setOutputFolder(absOutDir);

    // TODO: Port number, Jndi, Catalina_base and additional features

    try {
        serverConfiguration.write(file);
    } catch (IOException e) {
        throw new CoreException(new Status(IStatus.ERROR, JettyPlugin.PLUGIN_ID,
                "Failed to write tomcat context file at " + file.getAbsolutePath()));
    }

    return file;

}

From source file:org.cubictest.exporters.selenium.launch.LaunchConfigurationDelegate.java

License:Open Source License

public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor)
        throws CoreException {

    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }/*w w w  .j  a v  a 2  s .  com*/

    monitor.beginTask(MessageFormat.format("{0}...", new String[] { configuration.getName() }), 5);
    // check for cancellation
    if (monitor.isCanceled()) {
        return;
    }

    try {

        monitor.subTask("Verifying attributes");
        try {
            preLaunchCheck(configuration, launch, new SubProgressMonitor(monitor, 2));
        } catch (CoreException e) {
            if (e.getStatus().getSeverity() == IStatus.CANCEL) {
                monitor.setCanceled(true);
                return;
            }
            throw e;
        }
        // check for cancellation
        if (monitor.isCanceled()) {
            return;
        }

        serverPort = evaluatePort();
        seleniumClientProxyPort = evaluatePort();

        launch.setAttribute(CUBIC_UNIT_PORT, String.valueOf(serverPort));
        launch.setAttribute(SELENIUM_CLIENT_PROXY, String.valueOf(seleniumClientProxyPort));

        String mainTypeName = verifyMainTypeName(configuration);
        IVMRunner runner = getVMRunner(configuration, mode);

        File workingDir = verifyWorkingDirectory(configuration);
        String workingDirName = null;
        if (workingDir != null) {
            workingDirName = workingDir.getAbsolutePath();
        }

        // Environment variables
        String[] envp = getEnvironment(configuration);

        ArrayList<Object> vmArguments = new ArrayList<Object>();
        ArrayList<Object> programArguments = new ArrayList<Object>();
        collectExecutionArguments(configuration, vmArguments, programArguments);

        // VM-specific attributes
        Map<?, ?> vmAttributesMap = getVMSpecificAttributesMap(configuration);

        // Classpath
        String[] classpath = getClasspath(configuration);

        // Create VM config
        VMRunnerConfiguration runConfig = new VMRunnerConfiguration(mainTypeName, classpath);
        runConfig.setVMArguments((String[]) vmArguments.toArray(new String[vmArguments.size()]));
        runConfig.setProgramArguments((String[]) programArguments.toArray(new String[programArguments.size()]));
        runConfig.setEnvironment(envp);
        runConfig.setWorkingDirectory(workingDirName);
        runConfig.setVMSpecificAttributesMap(vmAttributesMap);

        // Bootpath
        runConfig.setBootClassPath(getBootpath(configuration));

        // check for cancellation
        if (monitor.isCanceled()) {
            return;
        }

        // done the verification phase
        monitor.worked(1);

        monitor.subTask("Create source locator description");
        // set the default source locator if required
        setDefaultSourceLocator(launch, configuration);
        monitor.worked(1);

        // Launch the configuration - 1 unit of work
        runner.run(runConfig, launch, monitor);

        // check for cancellation
        if (monitor.isCanceled()) {
            return;
        }

        IJavaProject project = getJavaProject(configuration);
        String fileName = getTestFileName(configuration);
        final IFile testFile = project.getProject().getFile(fileName);

        IWorkbench wb = PlatformUI.getWorkbench();
        IWorkbenchWindow wbw = wb.getActiveWorkbenchWindow();
        if (wbw == null)
            wbw = wb.getWorkbenchWindows()[0];
        IWorkbenchPage ap = wbw.getActivePage();
        if (ap == null)
            ap = wbw.getPages()[0];
        final IWorkbenchPage finalAp = ap;
        wb.getDisplay().syncExec(new Runnable() {
            public void run() {
                try {
                    GraphicalTestEditor editor = (GraphicalTestEditor) IDE.openEditor(finalAp, testFile);
                    setTest(editor.getTest());
                    setTestEditor(editor);
                    editor.getTest().resetStatus();
                    editor.getTest().refreshAndVerifySubFiles();
                } catch (Exception e) {
                    Logger.warn("Error opening test in editor", e);
                    setTest(TestPersistance.loadFromFile(testFile));
                }
            }
        });

        String browser = getBrowser(configuration);
        boolean useNamespace = useNamespace(configuration);

        seleniumHost = getSeleniumHost(configuration);

        seleniumPort = getSeleniumPort(configuration);
        if (seleniumPort < 0)
            seleniumPort = evaluatePort();

        seleniumMultiWindow = getSeleniumMultiWindow(configuration);

        // create the parameters:
        RunnerParameters parameters = new RunnerParameters();
        parameters.test = test;
        parameters.display = wb.getDisplay();
        parameters.remoteRunnerClientListenerPort = serverPort;
        parameters.seleniumClientProxyPort = seleniumClientProxyPort;

        SeleniumRunnerConfiguration config = new SeleniumRunnerConfiguration();
        if (!isSeleniumServerAutoHostAndPort(configuration)) {
            config.setUseExistingSeleniumServer(seleniumHost, seleniumPort);
        }
        config.setBrowser(BrowserType.fromId(browser));
        config.setMultiWindow(seleniumMultiWindow);
        config.setSupportXHtmlNamespaces(useNamespace);
        config.setHtmlCaptureAndScreenshotsTargetDir(workingDirName);
        config.setTakeScreenshots(getSeleniumTakeScreenshots(configuration));
        config.setCaptureHtml(getSeleniumCaptureHtml(configuration));

        verifyPreconditions(parameters, config);

        final ICubicTestRunnable cubicTestRunnable = getCubicTestRunnable(parameters, config);
        try {
            // run!
            cubicTestRunnable.run(monitor);

            // show result message
            wb.getDisplay().syncExec(new Runnable() {
                public void run() {
                    if (StringUtils.isNotBlank(cubicTestRunnable.getResultMessage())) {
                        final String msg = "Test run finished. " + cubicTestRunnable.getResultMessage();
                        UserInfo.showInfoDialog(msg);
                    }
                }
            });

            project.getResource().refreshLocal(IResource.DEPTH_ONE, null);
            IResource outputFolder = project.getProject()
                    .findMember(SeleniumHolder.HTML_AND_SCREENSHOTS_FOLDER_NAME);
            if (outputFolder != null) {
                outputFolder.refreshLocal(IResource.DEPTH_INFINITE, null);
            }
        } catch (final Exception e) {
            wb.getDisplay().syncExec(new Runnable() {
                public void run() {
                    ErrorHandler.logAndShowErrorDialog("Error when running test", e);
                }
            });
        } finally {
            cubicTestRunnable.cleanUp();
        }
    } catch (Exception e) {
        Logger.error("Error launching test", e);
    } finally {
        monitor.done();
    }
}