Example usage for org.eclipse.jdt.core IPackageFragmentRoot getPackageFragment

List of usage examples for org.eclipse.jdt.core IPackageFragmentRoot getPackageFragment

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IPackageFragmentRoot getPackageFragment.

Prototype

IPackageFragment getPackageFragment(String packageName);

Source Link

Document

Returns the package fragment with the given package name.

Usage

From source file:fr.imag.adele.cadse.cadseg.operation.MigrateCodePagesAction.java

License:Apache License

@Override
public void doFinish(UIPlatform uiPlatform, Object monitor) throws Exception {
    super.doFinish(uiPlatform, monitor);
    IProgressMonitor pmo = (IProgressMonitor) monitor;
    its_old = new HashMap<String, CItemType>();
    its_new = new HashMap<String, CItemType>();
    for (CItemType cit : oldCadse.getItemType()) {
        its_old.put(cit.getId(), cit);/*from   ww w .  j av  a2s.  co m*/
    }
    for (CItemType cit : newCadse.getItemType()) {
        its_new.put(cit.getId(), cit);
    }
    IFolder oldsources = oldProject.getFolder("sources");
    IJavaProject oldjp = JavaCore.create(oldProject);
    IPackageFragmentRoot joldsources = oldjp.getPackageFragmentRoot(oldsources);
    String oldCstClass = oldCadse.getCstClass();
    IPackageFragment pn = joldsources.getPackageFragment(getPackage(oldCstClass));
    String oldCstCn = getClassName(oldCstClass);
    ICompilationUnit cu = pn.getCompilationUnit(oldCstCn + ".java");
    IType cstType = cu.getType(oldCstCn);

    for (CItemType cit : oldCadse.getItemType()) {
        CItemType newcit = its_new.get(cit.getId());
        if (newcit == null) {
            continue;
        }
        String oldcst = cit.getCstName();
        String newcst = cit.getCstName();
        if (!oldcst.equals(newcst)) {
            IField cstField = cstType.getField(oldcst);
            if (cstField.exists()) {
                RenameSupport.create(cstField, newcst, RenameSupport.UPDATE_REFERENCES);
                cit.setCstName(newcst);
            }
        }
        HashMap<String, CLinkType> ltits_new = new HashMap<String, CLinkType>();

        for (CLink clt : newcit.getOutgoingLink()) {
            if (!(clt instanceof CLinkType))
                continue;
            ltits_new.put(((CLinkType) clt).getName(), (CLinkType) clt);
        }
        for (CLink clt : cit.getOutgoingLink()) {
            if (!(clt instanceof CLinkType))
                continue;

            CLinkType newclt = ltits_new.get(((CLinkType) clt).getName());
            if (newclt == null)
                continue;
            oldcst = ((CLinkType) clt).getCstName();
            newcst = newclt.getCstName();
            if (!oldcst.equals(newcst)) {
                IField cstField = cstType.getField(oldcst);
                if (cstField.exists()) {
                    RenameSupport.create(cstField, newcst, RenameSupport.UPDATE_REFERENCES);
                    ((CLinkType) clt).setCstName(newcst);
                }
            }
        }
        pmo.worked(1);
    }
    writeCadse(oldProject);
    // finish1(pmo);
}

From source file:hydrograph.ui.expression.editor.jar.util.BuildExpressionEditorDataSturcture.java

License:Apache License

public void createClassRepo(String jarFileName, String Package) {
    ClassRepo.INSTANCE.flusRepo();/*from  w w w  . j a  v  a  2 s. c  om*/
    try {
        IPackageFragmentRoot iPackageFragmentRoot = getIPackageFragment(jarFileName);
        if (iPackageFragmentRoot != null) {
            IPackageFragment fragment = iPackageFragmentRoot.getPackageFragment(Package);
            if (fragment != null) {
                for (IClassFile element : fragment.getClassFiles()) {
                    ClassRepo.INSTANCE.addClass(element, "", "", false);
                }
            } else {
                new CustomMessageBox(SWT.ERROR,
                        Package + " Package not found in jar " + iPackageFragmentRoot.getElementName(), "ERROR")
                                .open();
            }
        }
    } catch (JavaModelException e) {
        LOGGER.error("Error occurred while loading class from jar {}", jarFileName, e);
    }
    loadClassesFromSettingsFolder();
}

From source file:hydrograph.ui.expression.editor.jar.util.BuildExpressionEditorDataSturcture.java

License:Apache License

@SuppressWarnings("restriction")
public boolean loadUserDefinedClassesInClassRepo(String jarFileName, String packageName) {
    IPackageFragmentRoot iPackageFragmentRoot = getIPackageFragment(jarFileName);
    try {//from   w  w  w.  j a  v a  2s  .  c  om
        if (iPackageFragmentRoot != null) {
            IPackageFragment fragment = iPackageFragmentRoot.getPackageFragment(packageName);
            if (fragment != null
                    && StringUtils.equals(fragment.getClass().getSimpleName(), JAR_PACKAGE_FRAGMENT)) {
                for (IClassFile element : fragment.getClassFiles()) {
                    if (isValidCLassName(element.getElementName()))
                        ClassRepo.INSTANCE.addClass(element, jarFileName, packageName, true);
                }
                return true;
            } else {
                for (IJavaElement element : fragment.getChildren()) {
                    if (element instanceof ICompilationUnit) {
                        for (IJavaElement javaElement : ((ICompilationUnit) element).getChildren()) {
                            if (javaElement instanceof SourceType
                                    && isValidCLassName(javaElement.getElementName())) {
                                ClassRepo.INSTANCE.addClass((SourceType) javaElement, jarFileName, packageName,
                                        true);
                            }
                        }
                    }
                }
                return true;
            }
        } else {
            LOGGER.warn("Package not found in jar " + iPackageFragmentRoot.getElementName(), "ERROR");
        }
    } catch (JavaModelException e) {
        LOGGER.error("Error occurred while loading class from jar", e);
    }
    return false;
}

From source file:hydrograph.ui.validators.utils.ValidatorUtility.java

License:Apache License

/**
 * This method checks if java file is present under source folder or not.
 * @param filePath java file path. //  ww w . jav a 2 s. co  m
 * @return true if file is present otherwise false.
 */
public boolean isClassFilePresentOnBuildPath(String filePath) {
    if (filePath.contains(".")) {
        String packageName = filePath.substring(0, filePath.lastIndexOf('.'));
        String JavaFileName = filePath.substring(filePath.lastIndexOf('.') + 1);

        IJavaProject javaProject = null;

        ISelectionService selectionService = Workbench.getInstance().getActiveWorkbenchWindow()
                .getSelectionService();
        ISelection selection = selectionService.getSelection();

        if (selection instanceof IStructuredSelection) {
            Object element = ((IStructuredSelection) selection).getFirstElement();
            if (element instanceof IResource) {
                IProject project = ((IResource) element).getProject();
                javaProject = JavaCore.create(project);
            } else {
                javaProject = createJavaProjectThroughActiveEditor();
            }
        } else if (selection instanceof TextSelection) {
            javaProject = createJavaProjectThroughActiveEditor();
        }

        IPackageFragmentRoot[] ipackageFragmentRootList = null;
        try {
            ipackageFragmentRootList = javaProject.getPackageFragmentRoots();
        } catch (JavaModelException e) {
            logger.error("Unable to get jars which are on build path of project ", e);
        }
        for (IPackageFragmentRoot tempIpackageFragmentRoot : ipackageFragmentRootList) {
            if (!tempIpackageFragmentRoot.getElementName().contains("-sources")) {
                IPackageFragment packageFragment = tempIpackageFragmentRoot.getPackageFragment(packageName);
                if (!packageFragment.exists())
                    continue;
                else {
                    if (packageFragment.getCompilationUnit(JavaFileName + ".java").exists()
                            || packageFragment.getClassFile(JavaFileName + ".class").exists())
                        return true;
                }
            }
        }
    }
    return false;
}

From source file:io.sarl.eclipse.wizards.elements.AbstractNewSarlElementWizardPage.java

License:Apache License

/** Replies if the given filename is a SARL script or a generated Java file.
 *
 * @param packageFragment - the package in which the file should be search for.
 * @param filename - the filename to test.
 * @return <code>true</code> if a file (SALR or Java) with the given name exists.
 *//*from w ww . j  a  va2  s .co m*/
protected boolean isSarlFile(IPackageFragment packageFragment, String filename) {
    if (isFileExists(packageFragment, filename, this.sarlFileExtension)) {
        return true;
    }
    final IJavaProject project = getPackageFragmentRoot().getJavaProject();
    if (project != null) {
        try {
            final String packageName = packageFragment.getElementName();
            for (final IPackageFragmentRoot root : project.getPackageFragmentRoots()) {
                final IPackageFragment fragment = root.getPackageFragment(packageName);
                if (isFileExists(fragment, filename, JAVA_FILE_EXTENSION)) {
                    return true;
                }
            }
        } catch (JavaModelException exception) {
            // silent error
        }
    }
    return false;
}

From source file:it.unibz.instasearch.indexing.WorkspaceIndexerJDT.java

License:Open Source License

/**
 * @param doc/* ww w. j  av  a2s.  co  m*/
 * @return
 * @throws JavaModelException 
 */
private IClassFile getClassFile(SearchResultDoc doc) throws Exception {

    IWorkspaceRoot workspaceRoot = InstaSearchPlugin.getWorkspaceRoot();
    IJavaModel javaModel = JavaCore.create(workspaceRoot);

    String javaProjectName = doc.getProject().segment(0);
    IJavaProject proj = javaModel.getJavaProject(javaProjectName);

    if (proj == null)
        throw new Exception("Project " + javaProjectName + " not found");

    if (!proj.isOpen())
        proj.open(new NullProgressMonitor());

    javaModel.refreshExternalArchives(new IJavaElement[] { proj }, new NullProgressMonitor());

    IPath filePath = new Path(doc.getFilePath());
    String fileName = filePath.lastSegment();

    IPath jarPath = filePath.removeLastSegments(2); // remove pkg and filename
    IPackageFragmentRoot jar = null;
    IResource jarFile = workspaceRoot.findMember(jarPath);

    if (jarFile != null)
        jar = proj.getPackageFragmentRoot(jarFile);
    else
        jar = proj.getPackageFragmentRoot(jarPath.toString()); // external archive

    if (jar == null)
        throw new Exception("Jar " + jarPath + " not found in project " + doc.getProjectName());

    IPath pkgPath = filePath.removeLastSegments(1); // remove filename
    String pkgName = pkgPath.lastSegment();

    IPackageFragment pkg = jar.getPackageFragment(pkgName);

    if (pkg == null)
        throw new Exception("Package " + pkgName + " not found  in " + doc.getProjectName());

    IClassFile classFile = pkg.getClassFile(fileName);

    return classFile;
}

From source file:net.officefloor.eclipse.classpath.ClasspathUtil.java

License:Open Source License

/**
 * Opens the class path resource./*from   ww  w.j a  va  2  s . c o  m*/
 * 
 * @param resourcePath
 *            Path to the resource on the class path.
 * @param editor
 *            {@link AbstractOfficeFloorEditor} opening the resource.
 */
public static void openClasspathResource(String resourcePath, AbstractOfficeFloorEditor<?, ?> editor) {

    // Extensions
    final String CLASS_EXTENSION = ".class";
    final String SOURCE_EXTENSION = ".java";

    try {
        // Obtain the package and resource name
        int index = resourcePath.lastIndexOf('/');
        String packageName = (index < 0 ? "" : resourcePath.substring(0, index)).replace('/', '.');
        String resourceName = (index < 0 ? resourcePath : resourcePath.substring(index + 1)); // +1
        // to
        // skip
        // separator

        // Obtain the java project
        IJavaProject project = JavaCore.create(ProjectConfigurationContext.getProject(editor.getEditorInput()));

        // Iterate over the fragment roots searching for the file
        for (IPackageFragmentRoot root : project.getAllPackageFragmentRoots()) {

            // Attempt to obtain the package
            IPackageFragment packageFragment = root.getPackageFragment(packageName);
            if (!packageFragment.exists()) {
                continue; // must have package
            }

            // Handle if a java or class file
            if (JavaCore.isJavaLikeFileName(resourceName) || resourceName.endsWith(CLASS_EXTENSION)) {

                // Handle based on kind of fragment root
                int rootKind = root.getKind();
                switch (rootKind) {
                case IPackageFragmentRoot.K_BINARY:
                    // Binary, so ensure extension is class
                    if (resourceName.endsWith(SOURCE_EXTENSION)) {
                        resourceName = resourceName.replace(SOURCE_EXTENSION, CLASS_EXTENSION);
                    }

                    // Attempt to obtain and open the class file
                    IClassFile classFile = packageFragment.getClassFile(resourceName);
                    if (classFile != null) {
                        openEditor(editor, classFile);
                        return; // opened
                    }
                    break;

                case IPackageFragmentRoot.K_SOURCE:
                    // Source, so ensure extension is java
                    if (resourceName.endsWith(CLASS_EXTENSION)) {
                        resourceName = resourceName.replace(CLASS_EXTENSION, SOURCE_EXTENSION);
                    }

                    // Attempt to obtain the compilation unit (source file)
                    ICompilationUnit sourceFile = packageFragment.getCompilationUnit(resourceName);
                    if (sourceFile != null) {
                        openEditor(editor, sourceFile);
                        return; // opened
                    }
                    break;

                default:
                    throw new IllegalStateException("Unknown package fragment root kind: " + rootKind);
                }

            } else {
                // Not java file, so open as resource
                for (Object nonJavaResource : packageFragment.getNonJavaResources()) {
                    // Should only be opening files
                    if (nonJavaResource instanceof IFile) {
                        IFile file = (IFile) nonJavaResource;

                        // Determine if the file looking for
                        if (resourceName.equals(file.getName())) {
                            // Found file to open, so open
                            openEditor(editor, file);
                            return;
                        }
                    } else {
                        // Unknown resource type
                        throw new IllegalStateException(
                                "Unkown resource type: " + nonJavaResource.getClass().getName());
                    }
                }
            }
        }

        // Unable to open as could not find
        MessageDialog.openWarning(editor.getEditorSite().getShell(), "Open", "Could not find: " + resourcePath);

    } catch (Throwable ex) {
        // Failed to open file
        MessageDialog.openInformation(editor.getEditorSite().getShell(), "Open",
                "Failed to open '" + resourcePath + "': " + ex.getMessage());
    }
}

From source file:net.rim.ejde.internal.ui.wizards.NewResourceFileWizard.java

License:Open Source License

@Override
public boolean performFinish() {
    final IProject userSelectedProject = ProjectUtils
            .getProject(newResourceFileCreationPage.getUserSelectedProject());

    String fileName = newResourceFileCreationPage.getFileName();
    IFile newResourceFile = null;/* w  w w  .  j a  va 2 s.c  o  m*/
    IPackageFragmentRoot userSelectedSourceFolder = newResourceFileCreationPage.getUserSelectedSourceFolder();
    IPackageFragment userSelectedPackage = newResourceFileCreationPage.getUserSelectedPackage();

    String _resourcePackageId = newResourceFileCreationPage.getResourcePackageId();

    if (newResourceFileCreationPage.isValidPackage()) {
        // Package is valid. No need to find or create a package.
        newResourceFile = newResourceFileCreationPage.createNewFile();
    } else {
        // Package selected is invalid. First we try and find package within
        // project workspace.
        IPackageFragmentRoot sourceRoots[] = ProjectUtils.getProjectSourceFolders(userSelectedProject);
        try {
            IJavaElement foundPackageElement = null;

            for (IPackageFragmentRoot sourceRoot : sourceRoots) {
                IPackageFragment packageFragment = sourceRoot.getPackageFragment(_resourcePackageId);
                if (packageFragment.exists()) {
                    foundPackageElement = packageFragment;
                    break;
                }
            }
            if (foundPackageElement == null) {
                // Package could not be found. We must create the package.
                IPackageFragment newlyCreatedPackage = userSelectedSourceFolder
                        .createPackageFragment(_resourcePackageId, true, null);

                /*
                 * The following code uses reflection to access a private TreeViewer. I had to work through multiple levels of
                 * objects to access the private field. In the future this code can break, if the hierarchy for these classes
                 * or the names of these fields change. Once i access the TreeViewer i then refresh it. This allows the newly
                 * created package to be added to the Tree and prevents a NullPointerException.
                 */
                Field fieldToAccess = WizardNewFileCreationPage.class.getDeclaredField("resourceGroup"); //$NON-NLS-1$
                fieldToAccess.setAccessible(true);
                ResourceAndContainerGroup resourceGroup = ((ResourceAndContainerGroup) fieldToAccess
                        .get(newResourceFileCreationPage));

                fieldToAccess = ResourceAndContainerGroup.class.getDeclaredField("containerGroup"); //$NON-NLS-1$
                fieldToAccess.setAccessible(true);
                ContainerSelectionGroup containerGroup = ((ContainerSelectionGroup) fieldToAccess
                        .get(resourceGroup));

                fieldToAccess = ContainerSelectionGroup.class.getDeclaredField("treeViewer"); //$NON-NLS-1$
                fieldToAccess.setAccessible(true);
                TreeViewer treeViewer = ((TreeViewer) fieldToAccess.get(containerGroup));
                treeViewer.refresh();

                /*
                 * This code will set the container path to null if the above tree isn't refreshed when the package is
                 * created.
                 */
                newResourceFileCreationPage.setContainerFullPath(newlyCreatedPackage.getPath());

            } else {
                // Package was found in project. Change the container path
                // to the found package.
                newResourceFileCreationPage.setContainerFullPath(foundPackageElement.getPath());
            }

            newResourceFile = newResourceFileCreationPage.createNewFile();

        } catch (Throwable e) {
            logger.error("performFinish() error", e); //$NON-NLS-1$
        }
    }

    // if resource file is linked, we just return. Fix SDR213684
    if (newResourceFile.isLinked()) {
        return true;
    }

    String packageStmt = createPackageStatement(userSelectedPackage);
    FileOutputStream fout = null;

    try {
        if (fileName.endsWith(ResourceConstants.RRH_SUFFIX)) {
            // user enters .rrh file extension
            // 1. create package statement
            File resourceFile = newResourceFile.getLocation().toFile();

            if (resourceFile.length() == 0 && resourceFile.canWrite()) {
                fout = new FileOutputStream(resourceFile);
                new PrintStream(fout).println(packageStmt);
            }

            // 2. create associated .rrc root locale file if it doesn't
            // exist
            String rrcFileName = fileName.substring(0, fileName.lastIndexOf(".")) //$NON-NLS-1$
                    + ResourceConstants.RRC_SUFFIX;

            File rrcOSFile = new File(newResourceFile.getLocation().toFile().getParentFile(), rrcFileName);

            if (!rrcOSFile.exists()) {
                rrcOSFile.createNewFile();// TO->JDP
            }
        }

        if (fileName.endsWith(ResourceConstants.RRC_SUFFIX)) {
            // user enters .rrc file extension
            // if corresponding rrh file doesn't exist, create it and set
            // package statement
            // if corresponding .rrc root locale file doesn't exist, create
            // it as well
            String rrhFileName;
            String rrcRootLocaleFileName = null;
            String rrcRootLanguageLocaleFileName = null;
            boolean hasCountryCode = (fileName.indexOf("_") != fileName.lastIndexOf("_")); //$NON-NLS-1$ //$NON-NLS-2$

            if (fileName.contains("_")) { //$NON-NLS-1$
                rrhFileName = fileName.substring(0, fileName.indexOf("_")) + ResourceConstants.RRH_SUFFIX; //$NON-NLS-1$
                // set root rrc file name
                rrcRootLocaleFileName = fileName.substring(0, fileName.indexOf("_")) //$NON-NLS-1$
                        + ResourceConstants.RRC_SUFFIX;
                if (hasCountryCode) {
                    // set root language rrc file name
                    rrcRootLanguageLocaleFileName = fileName.substring(0, fileName.lastIndexOf("_")) //$NON-NLS-1$
                            + ResourceConstants.RRC_SUFFIX;
                }
            } else {
                rrhFileName = fileName.substring(0, fileName.lastIndexOf(".")) + ResourceConstants.RRH_SUFFIX; //$NON-NLS-1$
            }

            File rrhOSFile = new File(newResourceFile.getLocation().toFile().getParentFile(), rrhFileName);

            if (!rrhOSFile.exists()) {
                rrhOSFile.createNewFile();// // TO->JDP

                if (rrhOSFile.length() == 0 && rrhOSFile.canWrite()) {
                    fout = new FileOutputStream(rrhOSFile);
                    new PrintStream(fout).println(packageStmt);
                }
            }

            File rrcOSFile = null;
            // create .rrc root locale file if required
            if (rrcRootLocaleFileName != null) {
                rrcOSFile = new File(newResourceFile.getLocation().toFile().getParentFile(),
                        rrcRootLocaleFileName);

                if (!rrcOSFile.exists()) {
                    rrcOSFile.createNewFile();
                }
            }

            // create .rrc root language locale file if required
            if (rrcRootLanguageLocaleFileName != null) {
                rrcOSFile = new File(newResourceFile.getLocation().toFile().getParentFile(),
                        rrcRootLanguageLocaleFileName);

                if (!rrcOSFile.exists()) {
                    rrcOSFile.createNewFile();
                }
            }
        }
    } catch (Exception e) {
        logger.error("performFinish: Error creating file", e); //$NON-NLS-1$
        return false;
    } finally {
        try {
            if (null != fout)
                fout.close();
        } catch (IOException e) {
            logger.error("performFinish: Could not close the file", e); //$NON-NLS-1$
        }
    }

    // Fix for DPI224873. Project becomes out of sync, which results
    // in out
    // of sync errors. The below will refresh project.
    try {
        userSelectedProject.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
    } catch (CoreException e) {
        logger.error("performFinish: Error during project refresh", e); //$NON-NLS-1$
    }

    return true;
}

From source file:net.rim.ejde.internal.ui.wizards.NewResourceFileWizardPage.java

License:Open Source License

@Override
protected boolean validatePage() {
    // perform preliminary page validation with
    // WizardNewFileCreationPage.validatePage() method
    boolean validPage = super.validatePage();

    if (validPage) {
        if (!getFileName().matches("([A-Za-z0-9]+([_][A-Za-z0-9]+){0,2}.rrc)|([A-Za-z0-9]+.rrh)")) {
            setErrorMessage(Messages.INVALID_FILE_NAME);
            validPage = false;/* w  ww. j  a v  a 2 s .  c o m*/
        }
    }

    if (validPage) {
        /* ensures the user selected a package under an eclipse source directory */
        boolean sourceFolderExists = false;
        _userSelectedProject = getContainerFullPath().segment(0);
        String path = getContainerFullPath().toString();

        IPackageFragmentRoot sourceRoots[] = ProjectUtils
                .getProjectSourceFolders(ProjectUtils.getProject(_userSelectedProject));
        // Iterate through all source folders
        for (IPackageFragmentRoot sourceRoot : sourceRoots) {
            String sourcePath = sourceRoot.getPath().toString() + IPath.SEPARATOR;
            if (path.startsWith(sourcePath) && (path.length() > sourcePath.length())) {
                String selectedPackage = path.substring(sourcePath.length()).replaceAll("/", "."); //$NON-NLS-1$ //$NON-NLS-2$
                // Since our current code standard is 1.5 do not use 1.6 methods yet.
                if (!StringUtils.isEmpty(selectedPackage)
                        && sourceRoot.getPackageFragment(selectedPackage).exists()) {
                    sourceFolderExists = true;
                    _userSelectedPackage = sourceRoot.getPackageFragment(selectedPackage);
                    _userSelectedSourceFolder = sourceRoot;
                    break;
                }
            }
        }
        if (!sourceFolderExists) {
            setErrorMessage(Messages.INVALID_PARENT_FOLDER_WIZARD_PAGE);
            validPage = false;
        }
    }

    if (validPage) {
        try {
            /*
             * Here we get access to the private field linkedResourceGroup and get the URI information for the linked .rrh
             * file. We then parse that file to get its package information
             */
            Field field = WizardNewFileCreationPage.class.getDeclaredField("linkedResourceGroup"); //$NON-NLS-1$
            field.setAccessible(true);
            linkFileLocation = ((CreateLinkedResourceGroup) field.get(this)).getLinkTargetURI();

            // If file is not linked, skip next code.
            if (linkFileLocation == null) {
                _validPackage = true;
            } else {
                // Initialize the resourcePackageID to properly identify if the package is valid
                _resourcePackageId = null;

                File linkFile = new File(linkFileLocation);
                if (getFileName().endsWith(ResourceConstants.RRH_SUFFIX)) {
                    /*
                     * Resource file is a rrh file. We must determine if its going in the correct package.
                     */
                    if (linkFile.length() == 0) {
                        setErrorMessage(Messages.RRH_NO_PACKAGE_ERROR);
                        return false;
                    }
                    _resourcePackageId = PackageUtils.getRRHPackageID(linkFile);

                } else {
                    /*
                     * Resource file is a rrc file. We must determine the correct package with its corresponding rrh file.
                     */
                    String rrhFileName = getFileName();

                    if (rrhFileName.contains("_")) { //$NON-NLS-1$
                        rrhFileName = rrhFileName.substring(0, rrhFileName.indexOf("_")) //$NON-NLS-1$
                                + ResourceConstants.RRH_SUFFIX;
                    } else {
                        rrhFileName = rrhFileName.replace(ResourceConstants.RRC_SUFFIX,
                                ResourceConstants.RRH_SUFFIX);
                    }

                    File rrhFile = new File(linkFile.getParent() + File.separator + rrhFileName);
                    if (rrhFile.exists() && (rrhFile.length() != 0)) {
                        _resourcePackageId = PackageUtils.getRRHPackageID(rrhFile);
                    }
                }

                /*
                 * Get package selected by user within the new resource wizard dialog and ensure it matches the package
                 * described in the .rrh file.
                 */
                _userSelectedProject = getContainerFullPath().segment(0);
                if (_resourcePackageId == null) {
                    /*
                     * Resource header file could not be found or contains no package. Ensuring correct package will have to
                     * be left to user.
                     */
                    _validPackage = true;
                } else if (!_resourcePackageId.equals(_userSelectedPackage.getElementName())) {
                    setMessage(NLS.bind(Messages.INVALID_PACKAGE_SELECTED, _resourcePackageId),
                            IMessageProvider.WARNING);
                    _validPackage = false;
                } else {
                    _validPackage = true;
                }
            }
        } catch (Throwable e) {
            logger.error("Validation Error", e); //$NON-NLS-1$
        }
    }
    if (validPage) {
        // Add warning if existing sibling resource exist
        IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(_userSelectedProject);
        IFile foundSiblingFile = getSiblingFile(getFileName(), project);

        if (foundSiblingFile != null) {
            if (foundSiblingFile.isLinked()) {
                setMessage(NLS.bind(Messages.EXISTING_LINKED_SIBLING_FOUND_WARNING, foundSiblingFile.getName(),
                        getFileName()), IMessageProvider.WARNING);
            } else {
                setMessage(NLS.bind(Messages.EXISTING_COPIED_SIBLING_FOUND_WARNING, foundSiblingFile.getName(),
                        getFileName()), IMessageProvider.WARNING);
            }
        }
    }
    return validPage;
}

From source file:org.apache.tapestrytools.ui.internal.wizards.AddTapestryComponentWizard.java

License:Open Source License

/**
 * The worker method. It will find the container, create the file if missing
 * or just replace its contents, and open the editor on the newly created
 * file.//from   www .j  a  v a 2  s. c  o m
 */

private void doFinish(String projectName, String folderName, String packageName, String className,
        boolean createTemplate, IProgressMonitor monitor) throws CoreException {
    IProject project = ResourcesPlugin.getWorkspace().getRoot().findMember(projectName).getProject();//ProjectUtilities.getProject(projectName);
    IJavaProject javaProject = JavaCore.create(project);
    IPackageFragmentRoot src = null;
    IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
    for (IPackageFragmentRoot pfr : roots) {
        if (pfr.getPath().toString().equals(folderName)) {
            src = pfr;
            break;
        }
    }
    monitor.beginTask("Creating " + className, 3);
    IPackageFragment aimPackage = src.getPackageFragment(packageName);
    String classContent = "package " + packageName + ";\n\n";
    classContent += "public class " + className + " {\n\n";
    classContent += "}";
    aimPackage.createCompilationUnit(className + ".java", classContent, false, null);
    monitor.worked(1);

    if (createTemplate) {
        IPath templatePath = aimPackage.getPath();
        if (TapestryWizardUtils.isMavenProject(project)) {
            String javaPath = aimPackage.getPath().toString();
            String temPath = javaPath;
            if (javaPath.indexOf("/main/java/") > -1) {
                temPath = javaPath.replace("/main/java/", "/main/resources/");
            } else if (javaPath.indexOf("/test/java/") > -1) {
                temPath = javaPath.replace("/test/java/", "/test/resources/");
            }
            IPath tmpPath = new Path(temPath);
            if (tmpPath.isValidPath(temPath)) {
                templatePath = tmpPath;
            }
        }

        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        final IFile file = root.getFile(templatePath.append(className + ".tml"));
        try {
            InputStream stream = openContentStream();
            if (file.exists()) {
                file.setContents(stream, true, true, monitor);
            } else {
                file.create(stream, true, monitor);
            }
            stream.close();
        } catch (IOException e) {
        }
        monitor.worked(1);
        monitor.setTaskName("Opening file for editing...");
        getShell().getDisplay().asyncExec(new Runnable() {
            public void run() {
                IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
                try {
                    IDE.openEditor(page, file, true);
                } catch (PartInitException e) {
                }
            }
        });
    }

    monitor.worked(1);

}