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

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

Introduction

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

Prototype

IPackageFragmentRoot[] getPackageFragmentRoots() throws JavaModelException;

Source Link

Document

Returns all of the package fragment roots contained in this project, identified on this project's resolved classpath.

Usage

From source file:org.eclipse.emf.importer.java.builder.JavaEcoreBuilder.java

License:Open Source License

protected IPath analyzeProject(IProject project) throws Exception {
    // Walk the project looking for .java files to analyze.
    ///*from w w w  . ja  va2s  .  com*/
    IJavaProject javaProject = JavaCore.create(project);
    IPackageFragmentRoot[] packageFragmentRoots = javaProject.getPackageFragmentRoots();
    Set<IResource> visited = new HashSet<IResource>();
    for (int i = 0; i < packageFragmentRoots.length; ++i) {
        if (packageFragmentRoots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
            traverse((IContainer) packageFragmentRoots[i].getUnderlyingResource(), visited);
        }
    }

    for (Map.Entry<EGenericType, EGenericType> entry : ecoreEGenericTypeToJavaEGenericTypeMap.entrySet()) {
        EGenericType ecoreEGenericType = entry.getKey();
        EGenericType javaEGenericType = entry.getValue();
        EModelElement eModelElement = null;
        for (EObject eObject = ecoreEGenericType.eContainer(); eObject != null; eObject = eObject
                .eContainer()) {
            if (eObject instanceof EModelElement) {
                eModelElement = (EModelElement) eObject;
                break;
            }
        }
        RequiredClassifierType requiredClassifierType = ecoreEGenericType.eContainer() instanceof EClass
                || ecoreEGenericType.eContainer() instanceof EReference
                        ? RequiredClassifierType.CLASS
                        : eAttributes.contains(ecoreEGenericType.eContainer())
                                ? RequiredClassifierType.DATA_TYPE
                                : RequiredClassifierType.NONE;
        resolve(eModelElement, ecoreEGenericType, requiredClassifierType);
        if (javaEGenericType != null) {
            resolve(eModelElement, javaEGenericType, requiredClassifierType);
        }

        if (javaEGenericType != null) {
            resolve(eModelElement, ecoreEGenericType, javaEGenericType);
        }
    }

    for (Map.Entry<EGenericType, EGenericType> entry : ecoreEGenericTypeToJavaEGenericTypeMap.entrySet()) {
        EGenericType ecoreEGenericType = entry.getKey();
        EGenericType javaEGenericType = entry.getValue();
        EModelElement eModelElement = null;
        for (EObject eObject = ecoreEGenericType.eContainer(); eObject != null; eObject = eObject
                .eContainer()) {
            if (eObject instanceof EModelElement) {
                eModelElement = (EModelElement) eObject;
                break;
            }
        }

        if (javaEGenericType == null) {
            resolve(eModelElement, ecoreEGenericType, javaEGenericType);
        }
        used(ecoreEGenericType);
    }

    for (EStructuralFeature eStructuralFeature : eStructuralFeatures) {
        EGenericType eGenericType = eStructuralFeature.getEGenericType();
        EClassifier eClassifier = eGenericType.getERawType();

        // If we have resolved to an EClass but we have an EAttribute, we can change it to be an EReference.
        //
        if (eClassifier instanceof EClass && eStructuralFeature instanceof EAttribute) {
            EAttribute eAttribute = (EAttribute) eStructuralFeature;
            EClass container = eAttribute.getEContainingClass();
            EReference eReference = EcoreFactory.eINSTANCE.createEReference();
            eReference.setChangeable(eAttribute.isChangeable());
            eReference.setVolatile(eAttribute.isVolatile());
            eReference.setTransient(eAttribute.isTransient());
            eReference.setDerived(eAttribute.isDerived());
            eReference.setUnsettable(eAttribute.isUnsettable());
            eReference.setLowerBound(eAttribute.getLowerBound());
            eReference.setUpperBound(eAttribute.getUpperBound());
            eReference.setName(eStructuralFeature.getName());
            eReference.setEGenericType(eGenericType);
            eReference.getEAnnotations().addAll(eStructuralFeature.getEAnnotations());
            container.getEStructuralFeatures()
                    .add(container.getEStructuralFeatures().indexOf(eStructuralFeature), eReference);
            container.getEStructuralFeatures().remove(eStructuralFeature);
            eStructuralFeature = eReference;
        } else if (eClassifier instanceof EDataType && eStructuralFeature instanceof EReference) {
            EReference eReference = (EReference) eStructuralFeature;
            EClass container = eReference.getEContainingClass();
            EAttribute eAttribute = EcoreFactory.eINSTANCE.createEAttribute();
            eAttribute.setChangeable(eReference.isChangeable());
            eAttribute.setVolatile(eReference.isVolatile());
            eAttribute.setTransient(eReference.isTransient());
            eAttribute.setDerived(eReference.isDerived());
            eAttribute.setUnsettable(eReference.isUnsettable());
            eAttribute.setLowerBound(eReference.getLowerBound());
            eAttribute.setUpperBound(eReference.getUpperBound());
            eAttribute.setName(eStructuralFeature.getName());
            eAttribute.setEGenericType(eGenericType);
            eAttribute.getEAnnotations().addAll(eStructuralFeature.getEAnnotations());
            container.getEStructuralFeatures().remove(eStructuralFeature);
            eStructuralFeature = eAttribute;
            eReferenceToOppositeNameMap.remove(eReference);
        }

        if (eClassifier.getEPackage() == null) {
            error(CodeGenEcorePlugin.INSTANCE.getString("_UI_TheTypeDoesNotResolveCorrectly_message",
                    new Object[] { eClassifier.getInstanceTypeName() }));

            eGenericType = EcoreFactory.eINSTANCE.createEGenericType();
            eGenericType.setEClassifier(eClassifier instanceof EClass ? EcorePackage.Literals.EOBJECT
                    : EcorePackage.Literals.EJAVA_OBJECT);
        }
    }

    // Now we need to hook up opposites by finding the named feature in the type.
    //
    for (Map.Entry<EReference, String> entry : eReferenceToOppositeNameMap.entrySet()) {
        EReference eReference = entry.getKey();
        String oppositeName = entry.getValue();
        EClass eClass = (EClass) eReference.getEType();
        // TODO handle class cast exception better.
        EReference eOpposite = (EReference) eClass.getEStructuralFeature(oppositeName);
        if (eOpposite == null) {
            error(CodeGenEcorePlugin.INSTANCE.getString("_UI_TheAttributeIsNotAMemberOf_message",
                    new Object[] { oppositeName, eClass.getName() }));
        } else if (eOpposite.getEOpposite() != eReference && eOpposite.getEOpposite() != null) {
            error(CodeGenEcorePlugin.INSTANCE.getString("_UI_TheOppositeAlreadyHasOpposite_message",
                    new Object[] { oppositeName, eOpposite.getEOpposite().getName(),
                            eOpposite.getEOpposite().getEContainingClass().getName() }));
        } else {
            eReference.setEOpposite(eOpposite);
            eOpposite.setEOpposite(eReference);

            used(eOpposite);

            // Containers are transient by default unless explicitly annotated otherwise.
            //
            if (eOpposite.isContainment() && !transientEReferenceWithOpposite.contains(eReference)) {
                eReference.setTransient(true);
            }
        }
    }

    // Now we need to hook up keys by finding the named feature in the type.
    //
    for (Map.Entry<EReference, List<String>> entry : eReferenceToKeyNamesMap.entrySet()) {
        EReference eReference = entry.getKey();
        EClass eClass = (EClass) eReference.getEType();
        for (String keyName : entry.getValue()) {
            EStructuralFeature eKey = eClass.getEStructuralFeature(keyName);
            if (eKey == null) {
                error(CodeGenEcorePlugin.INSTANCE.getString("_UI_TheAttributeIsNotAMemberOf_message",
                        new Object[] { keyName, eClass.getName() }));
            } else if (!(eKey instanceof EAttribute)) {
                // TODO Ignore for now.
            } else {
                eReference.getEKeys().add((EAttribute) eKey);
                used(eKey);
            }
        }
    }

    // Clean up the temporary container annotations for holding map entry classes until they are for sure needed.
    //
    for (EPackage ePackage : packageNameToEPackageMap.values()) {
        EAnnotation eAnnotation = ePackage.getEAnnotation(MAP_ENTRY_CLASS_CONTAINER_ANNOTATION_SOURCE);
        if (eAnnotation != null) {
            EcoreUtil.remove(eAnnotation);
        }
    }

    // Now we should sort.
    //
    for (Map.Entry<EPackage, Map<Object, Integer>> entry : ePackageToOrderingMap.entrySet()) {
        EPackage ePackage = entry.getKey();
        Map<Object, Integer> nameToIDMap = entry.getValue();

        sort(ePackage.getEClassifiers(), nameToIDMap);
        for (EClassifier eClassifier : ePackage.getEClassifiers()) {
            if (eClassifier instanceof EClass) {
                EClass eClass = (EClass) eClassifier;
                sort(eClass.getEStructuralFeatures(), nameToIDMap);
            }
        }
    }

    // Find the fragment root so that we can generate to the right location (by default).
    //
    IPath targetFragmentRoot = project.getFullPath();
    for (int i = 0; i < packageFragmentRoots.length; ++i) {
        if (packageFragmentRoots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
            IPath path = packageFragmentRoots[i].getUnderlyingResource().getFullPath();
            if (targetFragmentRoot.isPrefixOf(path)) {
                targetFragmentRoot = path;
                break;
            }
        }
    }

    facadeHelper.reset();
    return targetFragmentRoot;
}

From source file:org.eclipse.emf.mwe.internal.ui.debug.sourcelookup.SourceLookupUtil.java

License:Open Source License

private static IPackageFragmentRoot getPackageFragmentRoot(final IRuntimeClasspathEntry entry) {
    IResource resource = entry.getResource();

    if (resource != null) {
        // our own project jars...
        IProject project = resource.getProject();
        IJavaProject jp = JavaCore.create(project);
        if (project.isOpen() && jp.exists()) {
            IPackageFragmentRoot root = jp.getPackageFragmentRoot(resource);
            return root;
        }//from w  ww  .java2s  .com
    }

    if (model == null) {
        model = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot());
    }

    // ... or external jars, that are registered in one of the open projects at runtime
    IPath reqPath = (resource == null ? new Path(entry.getLocation()) : entry.getPath());
    try {
        for (IJavaProject jp : model.getJavaProjects()) {
            if (jp.getProject().isOpen()) {
                for (IPackageFragmentRoot root : jp.getPackageFragmentRoots()) {
                    if (root.isExternal() && root.getPath().equals(reqPath)) {
                        return root;
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        Activator.logError(e); // should not occur
    }
    return null;
}

From source file:org.eclipse.emf.mwe2.language.ui.wizard.NewMwe2FileWizard.java

License:Open Source License

@Override
public void addPages() {
    super.addPages();
    mainPage = new WizardNewFileCreationPage("newFilePage1", getSelection()) { //$NON-NLS-1$
        @Override/*  ww w  . j  a va2  s .c  o m*/
        protected InputStream getInitialContents() {
            String module = getModule();
            if (module != null) {
                String content = String.format(Messages.NewMwe2FileWizard_initialContent, module);
                return new StringInputStream(content);
            }
            return new StringInputStream(""); //$NON-NLS-1$
        }

        protected String getModule() {
            IPath path = getContainerFullPath();
            IProject project = null;
            for (IProject p : workspace.getRoot().getProjects()) {
                if (p.getFullPath().isPrefixOf(path)) {
                    project = p;
                    break;
                }
            }
            IJavaProject javaProject = JavaCore.create(project);
            if (javaProject != null) {
                try {
                    IPackageFragmentRoot root = null;
                    for (IPackageFragmentRoot candidate : javaProject.getPackageFragmentRoots()) {
                        if (candidate.getPath().isPrefixOf(path)) {
                            root = candidate;
                            break;
                        }
                    }
                    if (root != null) {
                        IPath relativePath = path.makeRelativeTo(root.getPath());
                        String pack = relativePath.toString().replace('/', '.');
                        String fileName = getFileName();
                        fileName = fileName.substring(0, fileName.indexOf("." + extension)); //$NON-NLS-1$
                        String module = pack + "." + fileName; //$NON-NLS-1$
                        return module;
                    }
                } catch (JavaModelException e) {
                    logger.error(e.getMessage(), e);
                }
            }
            return null;
        }
    };
    mainPage.setTitle(Messages.NewMwe2FileWizard_title);
    mainPage.setDescription(Messages.NewMwe2FileWizard_description);
    mainPage.setFileExtension(extension);
    addPage(mainPage);
}

From source file:org.eclipse.emf.teneo.eclipse.genxml.RunGenerateJob.java

License:Open Source License

/** Determine the classnames of the interfaces */
private String getEPackageNames() {
    try {//w  w w  . ja va2  s. c  o  m
        final ArrayList<String> result = new ArrayList<String>();
        for (int i = 0; i < jProjects.size(); i++) {
            final IJavaProject ijp = jProjects.get(i);
            for (int j = 0; j < ijp.getPackageFragmentRoots().length; j++) {
                IPackageFragmentRoot ipf = ijp.getPackageFragmentRoots()[j];
                if (ipf.getClass().getName().endsWith("JarPackageFragmentRoot")) {
                    continue;
                }
                if (!ipf.exists()) {
                    continue;
                }
                for (int c = 0; c < ipf.getChildren().length; c++) {
                    walk(ipf.getChildren()[c], "", result);
                }
            }
        }

        StringBuffer resultStr = new StringBuffer();
        for (int i = 0; i < result.size(); i++) {
            final String epackage = result.get(i);
            if (i > 0) {
                resultStr.append(",");
            }
            resultStr.append(epackage);
        }
        return resultStr.toString();
    } catch (Exception e) {
        throw new StoreEclipseException("Exception while looking for epackages in projects " + e.getMessage(),
                e);
    }

}

From source file:org.eclipse.emf.texo.generator.EclipseGeneratorUtils.java

License:Open Source License

/** Returns the workspace path to the source directory */
public static String getSourceDirectory(final IProject project) {
    try {//from w w w .j a  va2s.  co  m
        final IJavaProject javaProject = JavaCore.create(project);
        final IPath sourcePath = javaProject.getPackageFragmentRoots()[0].getPath();
        return sourcePath.toString();
    } catch (final JavaModelException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.eclipse.fx.ide.css.validation.CssDslJavaValidator.java

License:Open Source License

@SuppressWarnings("restriction")
@Check/*from  w w  w . j a  v a  2s  . c  o m*/
public void checkDeclaration(css_declaration dec) {
    //      System.err.println("CHECK DECL " + dec);
    css_property property = dec.getProperty();

    // Only validate files who are:
    // * in a plug-in project
    //   - when css is part of build.properties bin.includes
    //   - when css is part of the source-folder
    IFile file = Utils.getFile(dec.eResource());

    //TODO We should add a service possibility to contribute these lookups
    boolean validate = false;

    try {
        if (file.getProject().hasNature("org.eclipse.pde.PluginNature")) { //$NON-NLS-1$
            // validate = true;
            IFile properties = PDEProject.getBuildProperties(file.getProject());
            Properties p = new Properties();
            try (InputStream in = properties.getContents()) {
                p.load(in);
                String includes = p.getProperty("bin.includes"); //$NON-NLS-1$
                if (includes != null) {
                    IPath path = file.getProjectRelativePath();
                    for (String s : includes.split(",")) { //$NON-NLS-1$
                        if (path.toString().startsWith(s.trim())) {
                            validate = true;
                            break;
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (!validate && file.getProject().hasNature("org.eclipse.jdt.core.javanature")) { //$NON-NLS-1$
            IJavaProject jp = JavaCore.create(file.getProject());
            for (IPackageFragmentRoot r : jp.getPackageFragmentRoots()) {
                if (r.getKind() == IPackageFragmentRoot.K_SOURCE) {
                    if (file.getProjectRelativePath().toString()
                            .startsWith(r.getPath().removeFirstSegments(1).toString())) {
                        validate = true;
                        break;
                    }
                }
            }
        }
    } catch (CoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if (!validate) {
        return;
    }

    if (dec.eContainer() instanceof font_face) {
        if ("font-family".equals(property.getName())) {
            if (dec.getValueTokens().stream().filter(this::filterWS).count() != 1) {
                error("Font family has to define a name", dec,
                        CssDslPackage.Literals.CSS_DECLARATION__VALUE_TOKENS);
            } else {
                if (!(dec.getValueTokens().stream().filter(this::filterWS).findFirst()
                        .get() instanceof IdentifierTok)) {
                    CssTok tok = dec.getValueTokens().stream().filter(this::filterWS).findFirst().get();
                    error("Invalid font family name", dec, CssDslPackage.Literals.CSS_DECLARATION__VALUE_TOKENS,
                            dec.getValueTokens().indexOf(tok));
                }
            }
        } else if ("src".equals(property.getName())) {
            if (dec.getValueTokens().stream().filter(this::filterWS).count() == 0) {
                error("At least one URL is required", dec,
                        CssDslPackage.Literals.CSS_DECLARATION__VALUE_TOKENS);
            } else {
                dec.getValueTokens().stream().filter(this::filterWS).filter(this::filterSymbol)
                        .filter((t) -> !(t instanceof UrlTok)).forEach((t) -> {
                            error("Only url-values are allowed", dec,
                                    CssDslPackage.Literals.CSS_DECLARATION__VALUE_TOKENS,
                                    dec.getValueTokens().indexOf(t));
                        });
            }
        } else if ("font-stretch".equals(property.getName())) {

        } else if ("font-style".equals(property.getName())) {

        } else if ("font-weight".equals(property.getName())) {

        } else if ("unicode-range".equals(property.getName())) {

        } else {
            warning("Unknown property: \"" + property.getName() + "\"", property,
                    CssDslPackage.Literals.CSS_PROPERTY__NAME);
        }

        return;
    }

    List<Proposal> properties = ext.getPropertyProposalsForSelector(file, dec, null);
    //extension.getAllProperties(uri);

    boolean known = false;
    for (Proposal p : properties) {
        if (p.getProposal().equals(property.getName())) {
            known = true;
            break;
        }
    }

    if (!known) {
        ICompositeNode node = NodeModelUtils.getNode(dec.getProperty());

        boolean suppress = node.getText().contains("@SuppressWarning");
        if (!suppress && !PREDEFINED_VAR_PROPS.contains(property.getName())
                && !property.getName().startsWith("-var")) { //$NON-NLS-1$
            warning("Unknown property: \"" + property.getName() + "\"", property,
                    CssDslPackage.Literals.CSS_PROPERTY__NAME);
        }
    } else {

        ruleset rs = (ruleset) dec.eContainer();
        List<selector> selectors = rs.getSelectors();
        //         Set<CssProperty> selectorProps = new HashSet<>();
        //         for (selector selector : selectors) {
        //            selectorProps.addAll(extension.getPropertiesForSelector(uri, selector));
        //         }

        List<Proposal> selectorProps = ext.getPropertyProposalsForSelector(Utils.getFile(dec.eResource()), dec,
                selectors);

        if (selectorProps.size() > 0) {
            boolean supported = false;
            for (Proposal p : selectorProps) {
                if (p.getProposal().equals(property.getName())) {
                    supported = true;
                    break;
                }
            }

            if (!supported) {
                ICompositeNode node = NodeModelUtils.getNode(dec.getProperty());

                boolean suppress = node.getText().contains("@SuppressWarning"); //$NON-NLS-1$

                if (!PREDEFINED_VAR_PROPS.contains(property.getName())
                        && !property.getName().startsWith("-var")) {
                    warning("\"" + property.getName() + "\" is not supported by the given selectors",
                            CssDslPackage.Literals.CSS_DECLARATION__PROPERTY);
                }
            }
        }

        //         List<ValidationResult> result = extension.validateProperty(uri, null, property.getName(), tokens);

        //         System.err.println(result);
        //
        //         System.err.println("validation of " + property.getName());

        //         if (!result.isEmpty()) {
        //            for (ValidationResult r : result) {
        //               if (r.status == ValidationStatus.ERROR) {
        //                  if (r.object != null) {
        //                     if (r.object instanceof FuncTok) {
        //                        FuncTok f = (FuncTok) r.object;
        //                        error(r.message, f, CssDslPackage.Literals.FUNC_TOK__NAME, -1);
        //                     }
        //                     else {
        //                        error(r.message, r.object, null, 0);
        //                     }
        //                  }
        //                  else {
        //                     error(r.message, dec, CssDslPackage.Literals.CSS_DECLARATION__VALUE_TOKENS, r.index);
        //                  }
        //               }
        //            }
        //         }
    }
}

From source file:org.eclipse.fx.ide.ui.util.RelativeFileLocator.java

License:Open Source License

public static File locateFile(URI uri, String filePath) {
    filePath = filePath.trim();//from   w ww .ja  va2s. co  m
    IProject p = ResourcesPlugin.getWorkspace().getRoot().getProject(uri.segment(1));
    IJavaProject jp = JavaCore.create(p);

    // Absolute to project
    if (filePath.startsWith("/")) {
        filePath = filePath.substring(1); // Remove the leading /
        IFile f = p.getFile(filePath);
        if (f.exists()) {
            return f.getLocation().toFile().getAbsoluteFile();
        } else if (jp != null) {
            try {
                for (IPackageFragmentRoot r : jp.getPackageFragmentRoots()) {
                    if (r.isArchive()) {
                        //TODO We should allow to load styles from the referenced jars
                    } else if (r.getResource() instanceof IFolder) {
                        IFolder folder = (IFolder) r.getResource();
                        if (folder.exists()) {
                            f = folder.getFile(filePath);
                            if (f.exists()) {
                                return f.getLocation().toFile().getAbsoluteFile();
                            }
                        }
                    }
                }
            } catch (JavaModelException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    } else {
        URI fileUri = null;

        try {
            fileUri = URI.createURI(filePath);
        } catch (Exception e) {
            // TODO: handle exception
        }

        if (fileUri != null && fileUri.isPlatformResource()) {
            Path path = new Path(fileUri.toPlatformString(true));
            IWorkspaceRoot root = jp.getProject().getWorkspace().getRoot();
            IFile file = root.getFile(path);
            if (file.exists()) {
                return file.getLocation().toFile().getAbsoluteFile();
            }
        } else {
            IPath path = null;
            for (int i = 2; i < uri.segmentCount() - 1; i++) {
                if (path == null) {
                    path = new Path(uri.segment(i));
                } else {
                    path = path.append(uri.segment(i));
                }
            }

            if (path != null) {
                IFile f = p.getFile(path.append(filePath));
                if (f.exists()) {
                    return f.getLocation().toFile().getAbsoluteFile();
                }
            }
        }
    }

    return null;
}

From source file:org.eclipse.gmf.tests.JDTUtil.java

License:Open Source License

private void collectProblems(IJavaElement jElement, IMemberProcessor[] processors) {
    try {/* w  w  w  .  j a v a2s .c  o m*/
        switch (jElement.getElementType()) {
        case IJavaElement.JAVA_PROJECT: {
            IJavaProject jProject = (IJavaProject) jElement;
            IPackageFragmentRoot[] roots = jProject.getPackageFragmentRoots();
            for (int i = 0; i < roots.length; i++) {
                if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
                    collectProblems(roots[i], processors);
                }
            }
        }
            break;
        case IJavaElement.PACKAGE_FRAGMENT_ROOT: {
            IPackageFragmentRoot root = (IPackageFragmentRoot) jElement;
            IJavaElement[] children = root.getChildren();
            for (int i = 0; i < children.length; i++) {
                collectProblems(children[i], processors);
            }
        }
            break;
        case IJavaElement.PACKAGE_FRAGMENT: {
            IPackageFragment pf = (IPackageFragment) jElement;
            ICompilationUnit[] compilationUnits = pf.getCompilationUnits();
            for (int i = 0; i < compilationUnits.length; i++) {
                collectProblems(compilationUnits[i], processors);
            }
        }
            break;
        case IJavaElement.COMPILATION_UNIT: {
            ICompilationUnit compilationUnit = (ICompilationUnit) jElement;
            IType[] types = compilationUnit.getTypes();
            for (int i = 0; i < types.length; i++) {
                collectProblems(types[i], processors);
            }
        }
            break;
        case IJavaElement.TYPE: {
            IMember member = (IMember) jElement;
            collectProblems(member, processors, false);
        }
            break;
        }
    } catch (JavaModelException e) {
        myAggregator.add(e.getStatus());
    }
}

From source file:org.eclipse.gmf.tests.setup.GenProjectBaseSetup.java

License:Open Source License

private void fixInstanceClasses(GenModel domainGenModel) {
    @SuppressWarnings("serial")
    class MultiMap<K, V> extends HashMap<K, LinkedList<V>> {

        public void putOne(K key, V value) {
            LinkedList<V> allForKey = get(key);
            if (allForKey == null) {
                allForKey = new LinkedList<V>();
                put(key, allForKey);/*from   w  w  w .j  av a 2  s .c o  m*/
            }
            allForKey.add(value);
        }
    }
    final MultiMap<String, GenClassifier> allInstanceClassNames = new MultiMap<String, GenClassifier>();
    for (GenPackage nextPackage : domainGenModel.getGenPackages()) {
        for (GenClassifier nextGenClassifier : nextPackage.getGenClassifiers()) {
            if (nextGenClassifier.getEcoreClassifier()
                    .eIsSet(EcorePackage.Literals.ECLASSIFIER__INSTANCE_CLASS_NAME)) {
                EClassifier ecoreClassifier = nextGenClassifier.getEcoreClassifier();
                allInstanceClassNames.putOne(ecoreClassifier.getInstanceClassName(), nextGenClassifier);
            }
        }
    }
    if (allInstanceClassNames.isEmpty()) {
        return;
    }

    IPackageFragmentRoot theRoot = null;
    IFile manifestFile = null;
    try {
        String pluginID = domainGenModel.getModelPluginID();
        IProject pluginProject = ResourcesPlugin.getWorkspace().getRoot().getProject(pluginID);
        IJavaProject javaProject = JavaCore.create(pluginProject);
        Assert.assertNotNull("Generated EMF model project is not a java project", javaProject);
        IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
        for (int i = 0; i < roots.length && theRoot == null; i++) {
            if (!roots[i].isReadOnly()) {
                theRoot = roots[i];
            }
        }

        manifestFile = pluginProject.getFile(JarFile.MANIFEST_NAME);
        Assert.assertNotNull("Writable project root not found in the generated project", theRoot);
        Assert.assertTrue("Manifest was not generated", manifestFile != null && manifestFile.exists());

        Manifest manifest = new Manifest(manifestFile.getContents());

        Attributes attributes = manifest.getMainAttributes();
        StringBuffer exportedPackages = new StringBuffer(attributes.getValue(Constants.EXPORT_PACKAGE));

        for (String instanceClassName : allInstanceClassNames.keySet()) {
            List<GenClassifier> eClassifiers = allInstanceClassNames.get(instanceClassName);
            Assert.assertFalse(eClassifiers.isEmpty());
            generateUserInterface(instanceClassName, eClassifiers, theRoot, exportedPackages);
        }

        attributes.putValue(Constants.EXPORT_PACKAGE, exportedPackages.toString());
        ByteArrayOutputStream contents = new ByteArrayOutputStream();
        manifest.write(contents);
        manifestFile.setContents(new ByteArrayInputStream(contents.toByteArray()), true, true,
                new NullProgressMonitor());
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail(e.getMessage());
    }
}

From source file:org.eclipse.imp.wizards.IMPWizard.java

License:Open Source License

public static String getProjectSourceLocation(IProject project) {
    try {//from  w  w  w  .j ava2  s.  com
        if (project == null)
            return null;
        JavaModel jm = JavaModelManager.getJavaModelManager().getJavaModel();
        IJavaProject jp = jm.getJavaProject(project);
        if (jp == null)
            return null;
        else {
            IPackageFragmentRoot[] roots = jp.getPackageFragmentRoots();
            for (int i = 0; i < roots.length; i++) {
                if (roots[i].getCorrespondingResource() instanceof IFolder) {
                    IPath lcnPath = roots[i].getPath();
                    lcnPath = lcnPath.removeFirstSegments(1);
                    String lcn = lcnPath.toString();
                    if (lcn.startsWith("/"))
                        lcn = lcn.substring(1);
                    if (!lcn.endsWith("/"))
                        lcn = lcn + "/";
                    return lcn;
                }
            }
        }
    } catch (JavaModelException e) {

    }
    return null;
}