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:eu.artist.migration.mdt.umlprofilediscovery.code2codemodel.util.JavaProjectManager.java

License:Open Source License

/**
 * //w w  w. ja  v  a2 s. c  o  m
 * @param project
 * @return
 */
public static URI createJavaProjectURI(IJavaProject project) {
    return URI.createURI(project.getElementName() + "_java_code_model.xmi");
}

From source file:eu.artist.migration.mdt.umlprofilediscovery.code2codemodel.util.JavaProjectManager.java

License:Open Source License

/**
 * /*w  ww.ja  v  a  2  s  . c  om*/
 * @param fragment
 * @param project
 * @return
 */
public static URI createJavaProjectURI(String fragment, IJavaProject project) {
    // TODO produce platform URI !!!
    return URI.createFileURI(
            new File(fragment + "/" + project.getElementName() + "_java_code_model.xmi").getAbsolutePath());
}

From source file:eu.artist.migration.mut.umlprofiler.ui.launch.J2PUMLLaunchDelegate.java

License:Open Source License

@Override
public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor)
        throws CoreException {
    // System.out.println("Pushed run ... start discovery ...");

    IResource[] resources = configuration.getMappedResources();
    IProject selectedProject = (IProject) resources[0];
    IJavaProject selectedJavaProject = JavaCore.create(selectedProject);

    String selectedDiscoverer = configuration.getAttribute(J2PUMLLaunchUtil.SELECTED_DISCOVERER,
            J2PUMLLaunchUtil.NO_DISCOVERY_SELECTION);

    // System.out.println("JavaProject: " + selectedJavaProject);
    // System.out.println("Selection: " + selectedDiscoverer);

    // run the UML Profile discovery
    if (selectedDiscoverer.equalsIgnoreCase(J2PUMLLaunchUtil.UML_PROFILE_DISCOVERY_SELECTION)) {
        // run the code2codemodel transformation - basically a small wrapper for MoDisco
        try {/*from  w  w w  .  j a  va2 s .  co  m*/
            Resource javaCodeModelResource = JavaDiscoverer.INSTANCE.runDiscovery(selectedJavaProject);
            javaCodeModelResource.setURI(URI
                    .createURI(selectedJavaProject.getElementName().concat(J2PUMLLaunchUtil.CODE_MODEL_PATH)));

            // once we have the Java Code Model we can run the transformation that produces the UML Profile
            CodeModel2UMLProfileWithResourceInjection runner = new CodeModel2UMLProfileWithResourceInjection();
            runner.setUmlProfilePath(
                    selectedJavaProject.getElementName().concat(J2PUMLLaunchUtil.UML_PROFILE_PATH));
            runner.setTraceModelPath(
                    selectedJavaProject.getElementName().concat(J2PUMLLaunchUtil.TRACE_MODEL_PATH));
            runner.loadModels(javaCodeModelResource, J2PUMLLaunchUtil.JP_MODEL_PATH,
                    J2PUMLLaunchUtil.JPT_MODEL_PATH, J2PUMLLaunchUtil.MC_MODEL_PATH,
                    J2PUMLLaunchUtil.UPT_MODEL_PATH, J2PUMLLaunchUtil.EPT_MODEL_PATH);
            runner.doCodeModel2UMLProfile(new NullProgressMonitor());

            // store the produced UML Profile
            File upsl = new File(selectedProject.getFullPath().toString());
            runner.saveUMLProfileModel(URI.createPlatformResourceURI(upsl.getAbsolutePath(), true)
                    .appendSegment(
                            selectedJavaProject.getElementName().concat(J2PUMLLaunchUtil.UML_PROFILE_PATH))
                    .toString());

            MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
                    "Success", "Profiled UML model created and saved in the respective project folder.");

        } catch (DiscoveryException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ATLCoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error",
                    "Profiled UML model could not be created.");
        }

    }

    // run the profiled UML model discovery
    else if (selectedDiscoverer.equalsIgnoreCase(J2PUMLLaunchUtil.PROFILED_UML_MODEL_DISCOVERY_SELECTION)) {
        // run the code2codemodel transformation - basically a small wrapper for MoDisco
        try {
            Resource javaCodeModelResource = JavaDiscoverer.INSTANCE.runDiscovery(selectedJavaProject);
            javaCodeModelResource.setURI(URI
                    .createURI(selectedJavaProject.getElementName().concat(J2PUMLLaunchUtil.CODE_MODEL_PATH)));

            // once we have the Java Code Model we can run the transformation that produces the profiled UML Model
            ProfiledUMLViewGenerator.INSTANCE.generateProfiledUMLView(javaCodeModelResource,
                    selectedJavaProject.getElementName(), selectedProject.getFullPath().toString());

            MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
                    "Success",
                    "Profiled UML Class diagram created and saved in the respective project folder.");

        } catch (DiscoveryException e) {
            e.printStackTrace();
            MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
                    "Discovery Error", "Profiled class diagram could not be created.");
        }
    }

    else if (selectedDiscoverer.equalsIgnoreCase(J2PUMLLaunchUtil.NO_DISCOVERY_SELECTION)) {
        // TODO Logging
    }
}

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

License:Apache License

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

    /*// w w w  . ja va  2s.c  o  m
     * 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.java.JavaProjectManager.java

License:Apache License

/**
 * Updates the classpath of the Java project associated with an item based
 * on changes in its dependencies./*from  ww  w.j a  v a2s. com*/
 * 
 * @param item
 *            the item
 * @param monitor
 *            the monitor
 * 
 * @return true, if update item dependencies classpath
 * 
 * @throws CoreException
 *             the core exception
 */
public static boolean updateItemDependenciesClasspath(Item item, IProgressMonitor monitor)
        throws CoreException {

    LogicalWorkspace model = CadseCore.getCadseDomain().getLogicalWorkspace();
    if (model == null || model.getState() != WSModelState.RUN) {
        return false;
    }
    if (ResourcesPlugin.getWorkspace().isTreeLocked()) {
        return false;
    }

    IJavaProject javaProject = getJavaProject(item);
    if (javaProject == null || !javaProject.exists()) {
        return false;
    }

    IClasspathContainer oldContainer = JavaCore
            .getClasspathContainer(ItemDependenciesClasspathEntry.CLASSPATH_ENTRY_PATH, javaProject);
    IClasspathContainer newContainer = new ItemDependenciesClasspathEntry(javaProject,
            javaProject.getElementName(), item, null, null);

    /*
     * Verify if the resolved dependencies actually changed
     */
    if (oldContainer != null) {
        if (Arrays.asList(oldContainer.getClasspathEntries())
                .equals(Arrays.asList(newContainer.getClasspathEntries()))) {
            return false;
        }
    }

    /*
     * Set the item dependencies container, this will trigger the Java
     * builder if needed.
     */
    JavaCore.setClasspathContainer(ItemDependenciesClasspathEntry.CLASSPATH_ENTRY_PATH,
            new IJavaProject[] { javaProject }, new IClasspathContainer[] { newContainer }, monitor);
    return true;
}

From source file:fr.imag.adele.fede.workspace.si.java.JobReloadClassPathMapping.java

License:Apache License

@Override
protected IStatus run(IProgressMonitor monitor) {
    if (monitor.isCanceled())
        return Status.OK_STATUS;
    testworkspaceToSleep(monitor);/*from  w  ww.j a v  a 2s . c o m*/
    if (monitor.isCanceled())
        return Status.OK_STATUS;
    if (model == null)
        return Status.OK_STATUS;
    Map<IJavaProject, IClasspathContainer> toset = new HashMap<IJavaProject, IClasspathContainer>();
    for (Item item : model.getItems()) {
        try {
            if (monitor.isCanceled())
                return Status.OK_STATUS;
            IJavaProject jp = item.getMainMappingContent(IJavaProject.class); // force
            // to
            // load
            // content
            if (jp == null) {
                continue;
            }

            IClasspathContainer cc = JavaCore
                    .getClasspathContainer(ItemDependenciesClasspathEntry.CLASSPATH_ENTRY_PATH, jp);
            if (cc == null) {
                toset.put(jp, new ItemDependenciesClasspathEntry(jp, jp.getElementName(), item, null, null));
                continue;
            }
            if (cc instanceof ItemDependenciesClasspathEntry) {
                if (((ItemDependenciesClasspathEntry) cc).isResolved()) {
                    continue;
                }
                toset.put(jp, new ItemDependenciesClasspathEntry(jp, jp.getElementName(), item, null, cc));
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
    if (toset.size() > 0) {
        try {
            // update classpath for all affected workspace plug-ins in
            // one operation
            IJavaProject[] jProjects = toset.keySet().toArray(new IJavaProject[toset.size()]);
            IClasspathContainer[] containers = toset.values().toArray(new IClasspathContainer[toset.size()]);
            JavaCore.setClasspathContainer(ItemDependenciesClasspathEntry.CLASSPATH_ENTRY_PATH, jProjects,
                    containers, null);
        } catch (JavaModelException e) {
        }
    }
    return Status.OK_STATUS;
}

From source file:fr.imag.exschema.Util.java

License:Open Source License

/**
 * Starting point for discovering schemas from all the versions stored in
 * the Git repository of the specified project.
 * //from  w w  w  .j ava2 s  .c om
 * @param project
 * @param monitor
 * @throws GitAPIException
 * @throws IOException
 * @throws CoreException
 * @throws InterruptedException
 */
public static List<File> discoverHistorySchemas(final IJavaProject project, final IProgressMonitor monitor)
        throws IOException, GitAPIException, InterruptedException, CoreException {
    File currentOutput;
    File renamedOutput;
    List<File> returnValue;
    List<Ref> projectVersions;

    projectVersions = GitUtil.getProjectVersions(project);
    returnValue = new ArrayList<File>(projectVersions.size());
    for (Ref version : projectVersions) {
        // Analyze project at this version
        Util.monitorSubtask(monitor, "Starting the analysis of version: " + version.getName());
        try {
            // Checkout and analyze this project version
            Util.monitorSubtask(monitor, "Checking out project version");
            GitUtil.checkoutProjectVersion(project, version.getName());
            Util.monitorSubtask(monitor, "Discovering schemas");
            currentOutput = Util.discoverSchemas(project, monitor);

            // Rename output directory with the version name
            Util.monitorSubtask(monitor, "Renaming results directory");
            renamedOutput = new File(currentOutput.getParentFile(),
                    version.getName().replaceAll("\\W", ".") + "-" + currentOutput.getName());
            currentOutput.renameTo(renamedOutput);
            returnValue.add(renamedOutput);
        } catch (Exception e) {
            Util.logger.log(Util.LOGGING_LEVEL, "Unable to discover schemas for project "
                    + project.getElementName() + " at version " + version.getName(), e);
        }
    }

    // Return project to the latest version
    Util.monitorSubtask(monitor, "Going back to the master branch");
    GitUtil.checkoutProjectVersion(project, "master");

    return returnValue;
}

From source file:io.sarl.eclipse.launching.shortcuts.LaunchAgentShortcut.java

License:Apache License

@SuppressWarnings("checkstyle:cyclomaticcomplexity")
private List<AgentDescription> findAgents(Object[] elements, IProgressService progress)
        throws InvocationTargetException, InterruptedException {
    final List<AgentDescription> descs = new ArrayList<>();
    progress.busyCursorWhile((monitor) -> {
        try {/*w ww  .  j a va2s .  c  o m*/
            monitor.beginTask(Messages.SARLLaunchShortcut_5, elements.length);
            for (final Object element : elements) {
                if (element instanceof SarlAgent) {
                    final SarlAgent agent = (SarlAgent) element;
                    final URI fileURI = agent.eResource().getURI();
                    for (final Pair<IStorage, IProject> storage : this.storage2UriMapper.getStorages(fileURI)) {
                        descs.add(new AgentDescription(storage.getSecond().getName(),
                                this.nameProvider.getFullyQualifiedName(agent).toString()));
                        break;
                    }
                } else {
                    final LinkedList<Object> stack = new LinkedList<>();
                    stack.add(element);
                    while (!stack.isEmpty()) {
                        final Object current = stack.removeFirst();
                        if (current instanceof IFile) {
                            final IFile file = (IFile) current;
                            final ResourceSet resourceSet = this.resourceSetProvider.get(file.getProject());
                            final URI resourceURI = URI.createPlatformResourceURI(file.getFullPath().toString(),
                                    true);
                            final Resource resource = resourceSet.getResource(resourceURI, true);
                            if (resource != null) {
                                final String projectName = file.getProject().getName();
                                for (final EObject content : resource.getContents()) {
                                    if (content instanceof SarlScript) {
                                        for (final SarlAgent agent : EcoreUtil2.getAllContentsOfType(content,
                                                SarlAgent.class)) {
                                            descs.add(new AgentDescription(projectName,
                                                    this.nameProvider.getFullyQualifiedName(agent).toString()));
                                        }
                                    }
                                }
                            }
                        } else if (current instanceof IType) {
                            final IType type = (IType) current;
                            final String qn = type.getFullyQualifiedName();
                            final IJavaProject project = type.getJavaProject();
                            if (this.jdt.isSubClassOf(this.jdt.toTypeFinder(project), qn,
                                    Agent.class.getName())) {
                                descs.add(new AgentDescription(project.getElementName(), qn));
                            }
                        } else if (current instanceof IPackageFragment) {
                            final IPackageFragment fragment = (IPackageFragment) current;
                            stack.addAll(Arrays.asList(fragment.getNonJavaResources()));
                            for (final Object child : fragment.getChildren()) {
                                stack.add(child);
                            }
                        } else if (current instanceof IPackageFragmentRoot) {
                            final IPackageFragmentRoot fragment = (IPackageFragmentRoot) current;
                            stack.addAll(Arrays.asList(fragment.getNonJavaResources()));
                            for (final Object child : fragment.getChildren()) {
                                stack.add(child);
                            }
                        } else if (current instanceof IJavaProject) {
                            stack.addAll(Arrays.asList(((IJavaProject) current).getNonJavaResources()));
                        }
                    }
                }
                monitor.worked(1);
            }
        } catch (JavaModelException exception) {
            throw new InvocationTargetException(exception);
        }
    });
    return descs;
}

From source file:it.scoppelletti.sdk.ide.projects.DependenciesContainer.java

License:Apache License

/**
 * Imposta per un progetto il class-path corrispondente alle dipendenze del
 * progetto stesso./*from  w ww .  j  a  v  a2 s  .  c  om*/
 * 
 * @param project Progetto.
 * @param monitor Gestore dell&rsquo;avanzamento.
 * @since         1.1.0
 */
public static void setClasspath(IJavaProject project, IProgressMonitor monitor) throws CoreException {
    String msg;
    DependenciesContainer.Builder builder;
    IClasspathContainer container;
    SubMonitor progress;

    if (project == null) {
        throw new NullPointerException("Argument project is null.");
    }

    msg = String.format("Calculating class-path \"%1$s\" for project \"%2$s\"...", DependenciesContainer.NAME,
            project.getElementName());
    progress = SubMonitor.convert(monitor, msg, 2);
    try {
        builder = new DependenciesContainer.Builder(project);
        container = new DependenciesContainer(builder.run(progress.newChild(1)));
        progress.worked(1);

        JavaCore.setClasspathContainer(container.getPath(), new IJavaProject[] { project },
                new IClasspathContainer[] { container }, progress.newChild(1));
        progress.worked(1);
    } finally {
        if (monitor != null) {
            monitor.done();
        }
    }
}

From source file:java5totext.input.JavaReader.java

License:Open Source License

/**
 * @param javaProject must be a javaProject from an Eclipse Workspace
 *///from   www . ja  va  2  s  .c o  m
public static Resource readModel(IJavaProject javaProject) {
    //Set resourceSet with the newly created model
    ResourceSet resourceSet = new ResourceSetImpl();

    Resource resource = resourceSet.createResource(URI.createFileURI("temp.j2se5"));

    Java5Factory factory = Java5Factory.eINSTANCE;
    BindingManager globalBindings = new BindingManager(factory);

    //Ceeation of the root element      
    Model resultModel = factory.createModel();
    resource.getContents().add(resultModel);

    try {
        if (javaProject != null) {
            resultModel.setName(javaProject.getElementName());

            IPackageFragment[] packageFolder = javaProject.getPackageFragments();
            int classCount = 0;

            // loop on CompilationUnit-s
            for (IPackageFragment parent : packageFolder) {
                ICompilationUnit[] children = parent.getCompilationUnits();

                for (ICompilationUnit cu : children) {
                    // Code parsing : here is indicated the version of jdk (~JLS) to consider, see Class comments
                    ASTParser parser = ASTParser.newParser(AST.JLS3);
                    parser.setResolveBindings(true);
                    parser.setSource(cu);
                    org.eclipse.jdt.core.dom.CompilationUnit parsedCompilationUnit = (CompilationUnit) parser
                            .createAST(null);

                    IProject aProject = javaProject.getProject();

                    try {
                        String filePathString = getRelativePath(aProject, parsedCompilationUnit);
                        IFile theIFile = ResourcesPlugin.getWorkspace().getRoot()
                                .getFile(parsedCompilationUnit.getJavaElement().getPath());
                        String fileContent = getContent(theIFile).toString();
                        JDTVisitor jdtVisitor = new JDTVisitor(factory, resultModel, globalBindings,
                                filePathString, fileContent);
                        parsedCompilationUnit.accept(jdtVisitor);

                        //                     CommentsManager.resolveCommentPositions(jdtVisitor);
                        //                     CommentsManager.resolveCommentContentsAndPositions(jdtVisitor.getCommentList(), fileContent, resultModel, 
                        //                           jdtVisitor.getNodesCreated(), jdtVisitor.getRootTypeOrEnum(),
                        //                           jdtVisitor.getRootRealStartPosition(), jdtVisitor.getRootRealEndPosition());
                        //                     List<Object> alleNodesCreated = new ArrayList<Object>(jdtVisitor.getNodesCreated());
                        //                     alleNodesCreated.addAll(jdtVisitor.getCommentList());
                        //                     LinePositionsManager.computeLineAndColumnPositions(fileContent, resultModel, alleNodesCreated,
                        //                           jdtVisitor.getRootTypeOrEnum(),   jdtVisitor.getRootRealStartPosition(), jdtVisitor.getRootRealEndPosition());                  
                    } catch (RuntimeException e) {
                        e.printStackTrace();
                    } catch (CoreException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    classCount++;
                }
            }

            globalBindings.resolveBindings(resultModel);
            MethodRedefinitionManager.resolveMethodRedefintions(resultModel);

            //            //Set resourceSet with the newly created model
            //            ResourceSet resourceSet = new ResourceSetImpl();
            //
            //            resourceSet.setResourceFactoryRegistry(new ResourceFactoryRegistryImpl());
            //            resourceSet.setPackageRegistry(new EPackageRegistryImpl());
            //            resourceSet.getResources().add(EcorePackage.eINSTANCE.eResource());
            //            resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("ecore", new EcoreResourceFactoryImpl());
            //
            //            resource = new XMIResourceImpl();
            //            resource.basicSetResourceSet(resourceSet, null);
            //
            //            resource.getContents().add(resultModel);      
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return resource;
}