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.talend.designer.core.ui.editor.properties.controllers.JavaCommandController.java

License:Open Source License

@Override
public Control createControl(Composite subComposite, final IElementParameter param, int numInRow, int nbInRow,
        int top, Control lastControl) {
    Button btnEdit;//w w  w .ja v a  2 s .co  m

    btnEdit = getWidgetFactory().createButton(subComposite, "", SWT.PUSH); //$NON-NLS-1$

    btnEdit.setImage(ImageProvider.getImage(CorePlugin.getImageDescriptor(DOTS_BUTTON)));
    FormData data;
    btnEdit.setData(NAME, JAVA_COMMAND);
    btnEdit.setData(PARAMETER_NAME, param.getName());
    btnEdit.addSelectionListener(new SelectionListener() {

        public void widgetDefaultSelected(SelectionEvent e) {
        }

        public void widgetSelected(SelectionEvent e) {
            // execute Java Command
            ElementParameter fullParam = (ElementParameter) param;
            File jar;
            URL url;
            try {
                List<URL> listURL = new ArrayList<URL>();
                ILibraryManagerService libManager = (ILibraryManagerService) GlobalServiceRegister.getDefault()
                        .getService(ILibraryManagerService.class);

                for (String jarString : fullParam.getJar().split(";")) {
                    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
                    IProject prj = root.getProject(JavaUtils.JAVA_PROJECT_NAME);
                    IJavaProject project = JavaCore.create(prj);
                    IPath libPath = project.getResource().getLocation().append(JavaUtils.JAVA_LIB_DIRECTORY);
                    libManager.retrieve(jarString, libPath.toPortableString(), new NullProgressMonitor());

                    jar = libPath.append(jarString).toFile();
                    url = jar.toURL();
                    listURL.add(url);
                }
                URLClassLoader urlClassLoader = new URLClassLoader(listURL.toArray(new URL[0]));
                Class<?> classLoaded = Class.forName(fullParam.getJavaClass(), true, urlClassLoader);
                Object object = classLoaded.newInstance();
                List<String> args = new ArrayList<String>();
                for (String arg : fullParam.getArgs()) {
                    args.add(ElementParameterParser.parse((Node) elem, arg));
                }
                for (Method method : classLoaded.getDeclaredMethods()) {
                    if (method.getName().equals(fullParam.getJavaFunction())) {
                        Object arglist[] = new Object[1];
                        arglist[0] = args.toArray(new String[0]);
                        method.invoke(object, arglist);
                    }
                }
            } catch (Exception e1) {
                MessageBoxExceptionHandler.process(e1);
            }
        }

    });
    if (elem instanceof Node) {
        btnEdit.setToolTipText(VARIABLE_TOOLTIP + param.getVariableName());
    }

    CLabel labelLabel = getWidgetFactory().createCLabel(subComposite, param.getDisplayName()); //$NON-NLS-1$
    data = new FormData();
    if (lastControl != null) {
        data.left = new FormAttachment(lastControl, 0);
    } else {
        data.left = new FormAttachment((((numInRow - 1) * MAX_PERCENT) / nbInRow), 0);
    }
    data.top = new FormAttachment(0, top);
    labelLabel.setLayoutData(data);
    if (numInRow != 1) {
        labelLabel.setAlignment(SWT.RIGHT);
    }
    // **************************
    data = new FormData();
    int currentLabelWidth = STANDARD_LABEL_WIDTH;
    GC gc = new GC(labelLabel);
    Point labelSize = gc.stringExtent(param.getDisplayName());
    gc.dispose();

    if ((labelSize.x + ITabbedPropertyConstants.HSPACE) > currentLabelWidth) {
        currentLabelWidth = labelSize.x + ITabbedPropertyConstants.HSPACE;
    }

    if (numInRow == 1) {
        if (lastControl != null) {
            data.left = new FormAttachment(lastControl, currentLabelWidth);
            data.right = new FormAttachment(lastControl, currentLabelWidth + STANDARD_BUTTON_WIDTH);
        } else {
            data.left = new FormAttachment(0, currentLabelWidth);
            data.right = new FormAttachment(0, currentLabelWidth + STANDARD_BUTTON_WIDTH);
        }
    } else {
        data.left = new FormAttachment(labelLabel, 0, SWT.RIGHT);
        data.right = new FormAttachment(labelLabel, STANDARD_BUTTON_WIDTH, SWT.RIGHT);
    }
    data.top = new FormAttachment(0, top);
    btnEdit.setLayoutData(data);
    // **************************
    hashCurControls.put(param.getName(), btnEdit);

    Point initialSize = btnEdit.computeSize(SWT.DEFAULT, SWT.DEFAULT);
    dynamicProperty.setCurRowSize(initialSize.y + ITabbedPropertyConstants.VSPACE);
    return btnEdit;
}

From source file:org.talend.repository.ui.wizards.exportjob.scriptsmanager.esb.JobJavaScriptOSGIForESBManager.java

License:Open Source License

@Override
protected List<URL> getExternalLibraries(boolean needLibraries, ExportFileResource[] process,
        Set<String> neededLibraries) {
    List<URL> list = new ArrayList<URL>();
    if (!needLibraries) {
        return list;
    }/*from w  ww  . j  ava  2  s  . c  o  m*/
    // jar from routines
    List<IRepositoryViewObject> collectRoutines = new ArrayList<IRepositoryViewObject>();
    boolean useBeans = false;
    if (GlobalServiceRegister.getDefault().isServiceRegistered(ICamelDesignerCoreService.class)) {
        ICamelDesignerCoreService camelService = (ICamelDesignerCoreService) GlobalServiceRegister.getDefault()
                .getService(ICamelDesignerCoreService.class);
        if (camelService.isInstanceofCamel(process[0].getItem())) {
            useBeans = true;
        }
    }
    // Lists all the needed jar files
    Set<String> listModulesReallyNeeded = new HashSet<String>();
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IProject prj = root.getProject(JavaUtils.JAVA_PROJECT_NAME);
    IJavaProject project = JavaCore.create(prj);
    IPath libPath = project.getResource().getLocation().append(JavaUtils.JAVA_LIB_DIRECTORY);
    File file = libPath.toFile();
    File[] files = file.listFiles(FilesUtils.getAcceptModuleFilesFilter());

    if (!useBeans) {
        // Gets all the jar files
        if (neededLibraries == null) {
            // in case export as been done with option "not recompile", then
            // libraires can't be retrieved when
            // build.
            IDesignerCoreService designerService = RepositoryPlugin.getDefault().getDesignerCoreService();
            for (int i = 0; i < process.length; i++) {
                ExportFileResource resource = process[i];
                ProcessItem item = (ProcessItem) resource.getItem();
                String version = item.getProperty().getVersion();
                if (!isMultiNodes() && this.getSelectedJobVersion() != null) {
                    version = this.getSelectedJobVersion();
                }
                ProcessItem selectedProcessItem;
                if (resource.getNode() != null) {
                    selectedProcessItem = ItemCacheManager.getProcessItem(
                            resource.getNode().getRoot().getProject(), item.getProperty().getId(), version);
                } else {
                    // if no node given, take in the current project only
                    selectedProcessItem = ItemCacheManager.getProcessItem(item.getProperty().getId(), version);
                }
                IProcess iProcess = designerService.getProcessFromProcessItem(selectedProcessItem);
                neededLibraries = iProcess.getNeededLibraries(true);
                if (neededLibraries != null) {
                    listModulesReallyNeeded.addAll(neededLibraries);
                }
            }
        } else {
            listModulesReallyNeeded.addAll(neededLibraries);
        }
    }

    collectRoutines.addAll(collectRoutines(process, useBeans));

    for (IRepositoryViewObject object : collectRoutines) {
        Item item = object.getProperty().getItem();
        if (item instanceof RoutineItem) {
            RoutineItem routine = (RoutineItem) item;
            EList imports = routine.getImports();
            for (Object o : imports) {
                IMPORTType type = (IMPORTType) o;
                listModulesReallyNeeded.add(type.getMODULE());
            }
        }
    }

    for (int i = 0; i < files.length; i++) {
        File tempFile = files[i];
        try {
            if (listModulesReallyNeeded.contains(tempFile.getName())) {
                list.add(tempFile.toURL());
            }
        } catch (MalformedURLException e) {
            ExceptionHandler.process(e);
        }
    }

    return list;
}

From source file:repast.simphony.agents.designer.core.AgentBuilderPlugin.java

License:Open Source License

/**
 * Adds classpath entries to the supported list.
 * //  w w w  . j  a  va  2 s  .  c  o  m
 * @param projectName
 * @param pathEntries
 */
public static void getResolvedClasspath(String projectName, List pathEntries) {

    IJavaProject javaProject = AgentBuilderPlugin.getJavaProject(projectName);
    IPath path = null;
    try {
        IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
        for (int i = 0; i < entries.length; i++) {
            IClasspathEntry entry = entries[i];
            path = null;
            if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
                path = getWorkspaceRoot().getLocation()
                        .append(JavaCore.getResolvedClasspathEntry(entry).getPath());
            } else if (entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
                path = JavaCore.getResolvedClasspathEntry(entry).getPath();
            } else if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                path = entry.getPath().makeAbsolute();
                if (!path.toFile().getAbsoluteFile().exists()) {
                    IPath location = getWorkspaceRoot().getProject(entry.getPath().segment(0))
                            .getFile(entry.getPath().removeFirstSegments(1)).getLocation();
                    if (location != null) {
                        File tmpFile = location.toFile();
                        if (tmpFile.exists())
                            path = location;
                    }
                }
            }
            if (path != null && !pathEntries.contains(path))
                pathEntries.add(path);

            if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
                IProject requiredProject = getWorkspaceProject(entry.getPath());
                // recurse into projects
                if (requiredProject != null)
                    getResolvedClasspath(requiredProject, pathEntries);
            }
        }
        IPath outputPath = javaProject.getOutputLocation();
        if (outputPath.segmentCount() == 1)
            outputPath = javaProject.getResource().getLocation();
        else
            outputPath = javaProject.getProject().getFile(outputPath.removeFirstSegments(1)).getLocation();
        if (outputPath != null && !pathEntries.contains(outputPath))
            pathEntries.add(outputPath);
    } catch (JavaModelException e) {
        AgentBuilderPlugin.log(e);
    }
}

From source file:ro.ieat.jmodex.api.jModexFacade.java

License:Open Source License

/**
 * Sets programmatically a preference for a project that is going to be analyzed. The preference names are 
 * constant strings specified at the beginning of this class.
 * //w  ww .  jav a 2s .c  om
 * @param theProject - the project for which we set some property
 * @param preferenceName - the name of the set property
 * @param preferenceValue - the value of the set property
 * @return - true in case of success, otherwise false
 */
public boolean setProjectPreference(IJavaProject theProject, String preferenceName, String preferenceValue) {
    try {
        if (preferenceName.equals(OUTPUTFILE) || preferenceName.equals(PREDEFINEDSPECIFIERSLIST)
                || preferenceName.equals(SPECIFIERSLIST) || preferenceName.equals(LOCALSABSTRACTION)
                || preferenceName.equals(DATABASEDATABASEDESCRIPTION)
                || preferenceName.equals(TOMCATSPECIFIEROPTIONS)) {
            theProject.getResource().setPersistentProperty(
                    new QualifiedName(Activator.PLUGIN_ID, preferenceName), preferenceValue);
            return true;
        }
    } catch (CoreException e) {
    }
    return false;
}

From source file:ro.ieat.jmodex.api.jModexFacade.java

License:Open Source License

/**
 * Creates a job object that will infer an ASLAN(++) model from 
 * the code of the specified project./*w  w  w. j a  va  2  s .c o m*/
 * 
 * @param theProject - the project that is going to be analyzed
 * @return - the created job object
 * 
 */
public Job inferModel(final IJavaProject theProject) {

    return new Job("Infer Aslan++ Model") {

        @Override
        protected IStatus run(IProgressMonitor monitor) {
            try {
                monitor.beginTask(this.getName(), 3);
                monitor.subTask("Build beharioral automaton");
                Job j1 = buildBehavioralAutomaton(theProject);
                j1.schedule();
                j1.join();
                if (j1.getResult().getException() != null) {
                    throw j1.getResult().getException();
                }
                if (monitor.isCanceled()) {
                    throw new CancelException();
                }
                Map<IMethod, MethodSummary> behaviour = ((BehavioralAutomatonStatus) j1.getResult())
                        .getResult();
                monitor.worked(1);
                monitor.subTask("Convert automaton to Aslan++");
                String modelName = ProjectPropertyPage.getProperty(theProject, ProjectPropertyPage.OUTPUTFILE);
                modelName = modelName.substring(modelName.lastIndexOf(File.separator) + 1,
                        modelName.lastIndexOf("."));
                Job j2 = translateIntoAslanpp(modelName, behaviour);
                j2.schedule();
                j2.join();
                if (j2.getResult().getException() != null) {
                    throw j2.getResult().getException();
                }
                if (monitor.isCanceled()) {
                    throw new CancelException();
                }
                AslanppModel am = ((TranslationStatus) j2.getResult()).getResult();
                monitor.worked(1);
                monitor.subTask("Write the model into file");
                File file = new File(
                        ProjectPropertyPage.getProperty(theProject, ProjectPropertyPage.OUTPUTFILE));
                PrintStream fos = new PrintStream(new FileOutputStream(file));
                StringBuilder text = new StringBuilder();
                am.print(0, text);
                fos.print(text);
                fos.close();
                theProject.getResource().refreshLocal(IResource.DEPTH_INFINITE, null);
                monitor.worked(1);
                return new InferModelStatus(file);
            } catch (Throwable e) {
                return new InferModelStatus(e);
            } finally {
                monitor.done();
            }
        }

    };

}

From source file:ro.ieat.jmodex.integration.ProjectPropertyPage.java

License:Open Source License

public static String getProperty(IJavaProject prj, String propName) {
    try {/*from ww  w . ja  v  a 2s . co  m*/
        String value = prj.getResource()
                .getPersistentProperty(new QualifiedName(Activator.PLUGIN_ID, propName));
        if (value == null) {
            if (propName.equals(OUTPUTFILE))
                value = prj.getResource().getLocation().toOSString() + File.separator + prj.getElementName()
                        + ".aslan++";
            else if (propName.equals(SPECIFIERSLIST)) {
                value = "";
            } else if (propName.equals(PREDEFINEDSPECIFIERSLIST)) {
                value = "";
            } else if (propName.equals(LOCALSABSTRACTION)) {
                value = "";
            } else if (propName.equals(DATABASEDESCRIPTION)) {
                value = "";
            } else if (propName.equals(TOMCATSPECIFIEROPTIONS)) {
                value = "";
            }
        }
        return value;
    } catch (CoreException e) {
        return null;
    }
}

From source file:runjettyrun.JettyLaunchConfigurationType.java

License:Apache License

private void addWebappAttr(ILaunchConfiguration configuration, List<String> runtimeVmArgs, String cfgAttr)
        throws CoreException {
    IJavaProject proj = this.getJavaProject(configuration);
    if (proj == null)
        return;/*www  . j a va  2  s  .c om*/

    String value = configuration.getAttribute(cfgAttr, "");

    if ("/".equals(value)) {
        IPath path = (IPath) proj.getResource().getLocation().clone();
        path.makeAbsolute();
        value = path.toOSString();
    } else {
        if (proj.getProject().getFolder(value).getLocation() == null) {
            throw new IllegalStateException("raw location shouldn't be null");
        }
        value = proj.getProject().getFolder(value).getLocation().toOSString();
    }

    if (value.length() == 0)
        return;

    String arg = "-Drjr" + "webapp" + "=" + value + "";
    runtimeVmArgs.add(arg);
    return;
}

From source file:x10dt.ui.launch.core.utils.ProjectUtils.java

License:Open Source License

/**
 * Returns the set of projects on this project's classpath.
 *//*from  w w  w.j  av a 2  s  .  co  m*/
public static Collection<IProject> getDependentProjects(IJavaProject project) throws JavaModelException {
    Collection<IProject> result = new ArrayList<IProject>();
    final IWorkspaceRoot root = project.getResource().getWorkspace().getRoot();
    for (final IClasspathEntry cpEntry : project.getResolvedClasspath(true)) {
        if (cpEntry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
            final IResource resource = root.findMember(cpEntry.getPath());
            if (resource == null) {
                LaunchCore.log(IStatus.WARNING, NLS.bind(Messages.JPU_ResourceErrorMsg, cpEntry.getPath()));
            } else {
                result.add((IProject) resource);
            }
        }
    }
    return result;
}

From source file:x10dt.ui.launch.core.utils.ProjectUtils.java

License:Open Source License

/**
 * Returns a filtered set of class path entries for a given Java project.
 * /*w w w . ja va  2s.c  om*/
 * @param <T> The type of the class path entries once transformed via the functor provided.
 * @param jProject The Java project to consider.
 * @param cpEntryFunctor The functor to use to transform an {@link IPath} related to a class path
 * entry into another type of interest.
 * @param libFilter The filter to user in order to filter the library entries.
 * @return A non-null, possibly empty, set of class path entries.
 * @throws JavaModelException Occurs if we could not resolve the class path entries.
 * @throws IllegalArgumentException Occurs if a class path entry kind is not one of the expected
 * list. More precisely, CPE_VARIABLE and CPE_CONTAINER should not be encountered.
 */
public static <T> Set<T> getFilteredCpEntries(final IJavaProject jProject,
        final IFunctor<IPath, T> cpEntryFunctor, final IFilter<IPath> libFilter, StringBuffer pathBuffer)
        throws JavaModelException {
    final Set<T> container = new HashSet<T>();
    final IWorkspaceRoot root = jProject.getResource().getWorkspace().getRoot();
    for (final IClasspathEntry cpEntry : jProject.getResolvedClasspath(true)) {
        collectCpEntries(container, cpEntry, root, libFilter, cpEntryFunctor, jProject.getProject(),
                pathBuffer);
    }
    return container;
}