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

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

Introduction

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

Prototype

boolean exists();

Source Link

Document

Returns whether this Java element exists in the model.

Usage

From source file:org.eclipse.wb.internal.core.nls.bundle.eclipse.AbstractAccessorSourceNewComposite.java

License:Open Source License

/**
 * Validate accessor fields./*from  w  ww  .  j  ava  2 s . c o  m*/
 */
protected void validateAccessorFields() {
    // validate source folder
    {
        IPackageFragmentRoot root = m_accessorPackageField.getRoot();
        if (root == null || !root.exists()) {
            setInvalid(KEY_ACCESSOR_FOLDER,
                    Messages.AbstractAccessorSourceNewComposite_validateAccessorSourceFolder);
        } else {
            setValid(KEY_ACCESSOR_FOLDER);
        }
    }
    // validate package
    String packageName = null;
    {
        IPackageFragment pkg = m_accessorPackageField.getPackage();
        packageName = pkg == null ? null : pkg.getElementName();
        if (pkg == null || !pkg.exists()) {
            setInvalid(KEY_ACCESSOR_PACKAGE,
                    Messages.AbstractAccessorSourceNewComposite_validateAccessorPackageEmpty);
        } else if (pkg.isDefaultPackage()) {
            setInvalid(KEY_ACCESSOR_PACKAGE,
                    Messages.AbstractAccessorSourceNewComposite_validateAccessorPackageDefault);
        } else {
            setValid(KEY_ACCESSOR_PACKAGE);
        }
    }
    // validate class name
    String className = m_accessorClassField.getText();
    {
        IStatus status = JavaConventions.validateJavaTypeName(className);
        if (className.indexOf('.') != -1) {
            setInvalid(KEY_ACCESSOR_CLASS,
                    Messages.AbstractAccessorSourceNewComposite_validateAccessorClassDot);
        } else if (status.getSeverity() != IStatus.OK) {
            setStatus(KEY_ACCESSOR_CLASS, status);
        } else {
            setValid(KEY_ACCESSOR_CLASS);
        }
        // if such class already exists, disable property group
        try {
            String fullClassName = packageName + "." + className;
            IType type = m_editor.getJavaProject().findType(fullClassName);
            setPropertyGroupEnable(type == null);
        } catch (Throwable e) {
            setInvalid(KEY_ACCESSOR_CLASS, "Exception: " + e.getMessage());
        }
    }
}

From source file:org.eclipse.wb.internal.core.utils.jdt.ui.PackageRootSelectionDialogField.java

License:Open Source License

/**
 * Tries to build a package fragment root out of a string and sets the string into this package
 * fragment root.//from   w w  w . ja v a2  s . c  o  m
 */
private static IPackageFragmentRoot getRootFromString(String rootString) {
    if (rootString.length() == 0) {
        return null;
    }
    // prepare resource for given string
    IPath path = new Path(rootString);
    IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
    IResource resource = workspaceRoot.findMember(path);
    if (resource == null) {
        return null;
    }
    // resource should be project or source folder
    int resourceType = resource.getType();
    if (resourceType == IResource.PROJECT || resourceType == IResource.FOLDER) {
        // check project
        IProject project = resource.getProject();
        if (!project.isOpen()) {
            return null;
        }
        // try to convert resource into package fragment root
        IJavaProject javaProject = JavaCore.create(project);
        IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(resource);
        if (root.exists()) {
            return root;
        }
    }
    return null;
}

From source file:org.eclipse.xtext.ui.containers.JavaProjectsStateHelper.java

License:Open Source License

protected IPackageFragmentRoot getJarWithEntry(URI uri) {
    Iterable<Pair<IStorage, IProject>> storages = getStorages(uri);
    IPackageFragmentRoot result = null;//from  w  w  w.j  a v a  2s .c  o  m
    for (Pair<IStorage, IProject> storage2Project : storages) {
        IStorage storage = storage2Project.getFirst();
        if (storage instanceof IJarEntryResource) {
            IPackageFragmentRoot fragmentRoot = ((IJarEntryResource) storage).getPackageFragmentRoot();
            if (fragmentRoot != null) {
                // IPackageFragmentRoot has some unexpected caching - it may return a different project
                // thus we use the one that was used to record the IPackageFragmentRoot
                IProject actualProject = storage2Project.getSecond();
                IJavaProject javaProject = JavaCore.create(actualProject);
                if (!javaProject.exists()) {
                    javaProject = fragmentRoot.getJavaProject();
                }
                if (isAccessibleXtextProject(javaProject.getProject())) {
                    // if both projects are the same - fine
                    if (javaProject.equals(fragmentRoot.getJavaProject()))
                        return fragmentRoot;
                    // otherwise re-obtain the fragment root from the real project
                    if (fragmentRoot.isExternal()) {
                        IPackageFragmentRoot actualRoot = javaProject
                                .getPackageFragmentRoot(fragmentRoot.getPath().toString());
                        if (actualProject.exists()) {
                            return actualRoot;
                        }
                    } else {
                        IPackageFragmentRoot actualRoot = javaProject
                                .getPackageFragmentRoot(fragmentRoot.getResource());
                        if (actualRoot.exists()) {
                            return actualRoot;
                        }
                    }
                    result = fragmentRoot;
                }
                if (result == null)
                    result = fragmentRoot;
            }
        }
    }
    return result;
}

From source file:org.eclipse.xtext.ui.resource.PackageFragmentRootWalker.java

License:Open Source License

public T traverse(IPackageFragmentRoot root, boolean stopOnFirstResult) throws JavaModelException {
    T result = null;//from   www.  ja v  a2s. c  o  m
    if (root.exists() && existsPhysically(root)) {
        Object[] resources = root.getNonJavaResources();
        TraversalState state = new TraversalState(root);
        for (Object object : resources) {
            if (object instanceof IJarEntryResource) {
                result = traverse((IJarEntryResource) object, stopOnFirstResult, state);
                if (stopOnFirstResult && result != null)
                    return result;
            }
        }

        IJavaElement[] children = root.getChildren();
        for (IJavaElement javaElement : children) {
            if (javaElement instanceof IPackageFragment) {
                result = traverse((IPackageFragment) javaElement, stopOnFirstResult, state);
                if (stopOnFirstResult && result != null)
                    return result;
            }
        }
    }
    return result;
}

From source file:org.eclipse.xtext.ui.resource.Storage2UriMapperJavaImpl.java

License:Open Source License

private Object computeModificationStamp(IPackageFragmentRoot root) {
    try {/*w  w  w  . ja va  2s .c o m*/
        if (root.exists()) {
            IResource resource = root.getUnderlyingResource();
            if (resource != null) {
                Object result = getLastModified(resource);
                if (result != null) {
                    return result;
                }
            }
            return root.getPath().toFile().lastModified();
        }
    } catch (CoreException e) {
        log.error(e.getMessage(), e);
    }
    return new Object();
}

From source file:org.eclipse.xtext.ui.resource.Storage2UriMapperJavaImpl.java

License:Open Source License

/**
 * @since 2.5/*from  ww  w. j ava 2  s  . c  o  m*/
 */
@Override
public URI getUri(/* @NonNull */ IStorage storage) {
    if (storage instanceof IJarEntryResource) {
        final IJarEntryResource casted = (IJarEntryResource) storage;
        IPackageFragmentRoot packageFragmentRoot = casted.getPackageFragmentRoot();
        Map<URI, IStorage> data = getAllEntries(packageFragmentRoot);
        for (Map.Entry<URI, IStorage> entry : data.entrySet()) {
            if (entry.getValue().equals(casted))
                return entry.getKey();
        }
        if (packageFragmentRoot.exists() && packageFragmentRoot.isArchive()) {
            IPath jarPath = packageFragmentRoot.getPath();
            URI jarURI;
            if (packageFragmentRoot.isExternal()) {
                jarURI = URI.createFileURI(jarPath.toOSString());
            } else {
                jarURI = URI.createPlatformResourceURI(jarPath.toString(), true);
            }
            URI result = URI.createURI("archive:" + jarURI + "!" + storage.getFullPath());
            return result;
        }
    }
    return null;
}

From source file:org.entirej.ide.ui.utils.JavaAccessUtils.java

License:Apache License

public static IPackageFragment[] choosePackage(Shell shell, IJavaProject javaProject, String filter,
        Boolean multipleSelection, IPackageFragmentFilter packageFragmentFilter) {
    List<IPackageFragment> elements = new ArrayList<IPackageFragment>();
    if (javaProject.exists()) {
        try {/*from w  w  w  .jav  a2  s . c o m*/
            IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
            for (int i = 0; i < roots.length; i++) {
                if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
                    IPackageFragmentRoot sourceRoot = roots[i];
                    if (sourceRoot != null && sourceRoot.exists()) {
                        IJavaElement[] children = sourceRoot.getChildren();
                        for (IJavaElement element : children) {
                            if (element instanceof IPackageFragment && (packageFragmentFilter == null
                                    || packageFragmentFilter.acccept((IPackageFragment) element)))
                                elements.add((IPackageFragment) element);
                        }
                    }
                }
            }
        } catch (JavaModelException e) {
            EJCoreLog.logException(e);
        }
    }

    ElementListSelectionDialog dialog = new ElementListSelectionDialog(shell,
            new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT));
    dialog.setIgnoreCase(false);
    dialog.setTitle("Package Selection");
    dialog.setMessage("Choose a folder");
    dialog.setFilter(filter);
    dialog.setMultipleSelection(multipleSelection);
    dialog.setEmptyListMessage("");
    dialog.setElements(elements.toArray(new IPackageFragment[0]));
    dialog.setHelpAvailable(false);

    if (dialog.open() == Window.OK) {
        Object[] result = dialog.getResult();
        IPackageFragment[] fragments = new IPackageFragment[result.length];
        for (int i = 0; i < result.length; i++) {
            fragments[i] = (IPackageFragment) result[i];
        }
        return fragments;

    }
    return new IPackageFragment[0];
}

From source file:org.entirej.ide.ui.utils.PackageAssistProvider.java

License:Apache License

public IContentProposal[] getProposals(String currentContent, int position) {
    final List<TypeProposal> proposals = new ArrayList<TypeProposal>();

    if (currentContent.length() > position) {
        currentContent = currentContent.substring(0, position);
    }//from   w  w  w .  ja  va 2 s .co m
    IJavaProject javaProject = projectProvider.getJavaProject();
    if (javaProject == null)
        return new IContentProposal[0];

    if (javaProject.exists()) {
        try {
            IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
            for (int i = 0; i < roots.length; i++) {
                if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
                    IPackageFragmentRoot sourceRoot = roots[i];
                    if (sourceRoot != null && sourceRoot.exists()) {
                        IJavaElement[] children = sourceRoot.getChildren();
                        for (IJavaElement element : children) {
                            if (element instanceof IPackageFragment) {

                                if (filterPkg(currentContent, position, element.getElementName())) {
                                    IPackageFragment fragment = (IPackageFragment) element;
                                    proposals.add(new TypeProposal(new Type(element.getElementName(),
                                            fragment.hasChildren() ? PKG_IMG : PKG_IMG_EMPTY), null));
                                }
                            }
                        }
                    }
                }
            }
        } catch (JavaModelException e) {
            EJCoreLog.logException(e);
        }
    }

    Collections.sort(proposals, new Comparator<TypeProposal>() {

        public int compare(TypeProposal o1, TypeProposal o2) {

            return o1.type.pkg.compareTo(o2.type.pkg);
        }
    });
    return proposals.toArray(new IContentProposal[0]);
}

From source file:org.fastcode.util.JUnitCreator.java

License:Open Source License

/**
 *
 * @param typeToWorkOn//from   ww w. ja  v a2 s  .c  o  m
 * @param method
 * @return
 * @throws Exception
 */
public static IMember generateTest(final IType type,
        final Map<Object, List<FastCodeEntityHolder>> commitMessage, final IMethod... methods)
        throws Exception {

    final VersionControlPreferences versionControlPreferences = VersionControlPreferences.getInstance();

    if (JunitPreferences.getInstance(type) == null) {
        throw new Exception(
                "Please select the correct project in Windows->Preferences->Fast Code->Unit Test and try again.");
    }
    final CreateUnitTestData createUnitTestData = getCreateUnitTestData(type, methods);

    if (createUnitTestData == null) {
        return null;
    }
    final JunitPreferencesAndType junitPreferencesAndType = createUnitTestData.getJunitPreferencesAndType(); // JUnitUtil.findJunitPreferences(type,
    // createUnitTestData.getJunitTestProfileName());
    /*
     * if (junitPreferencesAndType == null) { throw new
     * Exception("This class you selected does not match any profile. " +
     * "Please configure it first by going to Window -> Preference -> Fast Code Pereference."
     * ); }
     */
    JunitPreferences junitPreferences = junitPreferencesAndType.getJunitPreferences();
    IType typeToWorkOn = junitPreferencesAndType.getType();
    /*
     * junitPreferences.setExpTest(createUnitTestData.getUnitTestType() ==
     * UNIT_TEST_TYPE.EXCEPTION_TEST);
     * junitPreferences.setHandleException(createUnitTestData
     * .getHandleException());
     * junitPreferences.setResultFormatList(Arrays.asList
     * (createUnitTestData.getUnitTestRsltFormatSelected()));
     * junitPreferences
     * .setMethodReturnType(createUnitTestData.getMethodReturnType());
     */
    junitPreferences.setCreateUnitTestData(createUnitTestData);

    // String junitTestLocation =
    // replacePlaceHolder(junitPreferences.getJunitTestLocation(),
    // "project", type.getJavaProject().getElementName());
    // junitTestLocation = "/" + junitTestLocation;

    final GlobalSettings globalSettings = getInstance();

    String junitTestLocation = globalSettings.isUseDefaultForPath() ? globalSettings.getSourcePathTest()
            : junitPreferences.getJunitTestLocation();
    junitTestLocation = getDefaultPathFromProject(typeToWorkOn.getJavaProject(), "test", junitTestLocation);
    final IPackageFragmentRoot testPackageFragmentRoot = SourceUtil
            .getPackageRootFromProject(typeToWorkOn.getJavaProject(), junitTestLocation);

    if (testPackageFragmentRoot == null || !testPackageFragmentRoot.exists()) {
        throw new Exception("Path does not exist in the project " + junitTestLocation);
    }

    // final String junitTestClassName =
    // junitPreferences.getJunitTestClass();
    final String junitBase = junitPreferences.getJunitBaseType();
    // final boolean createMethodBody =
    // junitPreferences.isCreateMethodBody();
    // final boolean alwaysCreateTryCatch =
    // junitPreferences.isAlwaysCreateTryCatch();
    // final boolean createInstance = junitPreferences.isCreateInstance();
    // final String[] methodAnnotations =
    // junitPreferences.getMethodAnnotations();

    ICompilationUnit unitTestCU = findTestUnit(typeToWorkOn, junitPreferences);
    // find the interface if unit test is null
    if (unitTestCU == null && typeToWorkOn.isClass()) {
        final IType tmpType = findSuperInterfaceType(typeToWorkOn);
        if (tmpType != null) {
            final JunitPreferences junitPref = JunitPreferences.getInstance(tmpType);
            if (junitPref != null) {
                unitTestCU = findTestUnit(tmpType, junitPref);
                if (unitTestCU != null) {
                    junitPreferences = junitPref;
                    typeToWorkOn = tmpType;
                    /*
                     * junitPreferences.setExpTest(createUnitTestData.
                     * getUnitTestType() == UNIT_TEST_TYPE.EXCEPTION_TEST);
                     * junitPreferences
                     * .setHandleException(createUnitTestData
                     * .getHandleException());
                     * junitPreferences.setResultFormatList
                     * (Arrays.asList(createUnitTestData
                     * .getUnitTestRsltFormatSelected()));
                     * junitPreferences.setMethodReturnType
                     * (createUnitTestData.getMethodReturnType());
                     */
                    junitPreferences.setCreateUnitTestData(createUnitTestData);
                }
            }
        }
    }

    if (!typeToWorkOn.equals(type) && checkForErrors(typeToWorkOn.getCompilationUnit().getResource())) {
        if (!MessageDialog.openQuestion(new Shell(), "Error",
                "There seems to be some problems associated with " + typeToWorkOn.getElementName()
                        + ". It is better to fix those problems and try again. Do you want to continue?")) {
            return null;
        }
    }

    IType junitBaseType = null;

    final JUNIT_TYPE junitType = junitPreferences.getJunitType();
    if (junitType == JUNIT_TYPE.JUNIT_TYPE_3) {
        junitBaseType = typeToWorkOn.getJavaProject().findType(junitBase);
        if (junitBaseType == null || !junitBaseType.exists()) {
            throw new Exception("Unable to find Junit Base Class " + junitBase + " in the current project. "
                    + "Make sure you have configured it properly by going to Windows -> Preference ->Fast Code Preference");
        }
    }

    final String testPkg = typeToWorkOn.getPackageFragment().getElementName();
    IPackageFragment testPackageFragment = testPackageFragmentRoot.getPackageFragment(testPkg);

    if (testPackageFragment == null || !testPackageFragment.exists()) {
        testPackageFragment = testPackageFragmentRoot.createPackageFragment(testPkg, false, null);
    }

    //final String testFormat = junitPreferences.getTestFormat();
    final String instance = createDefaultInstance(typeToWorkOn.getElementName());
    final CreateSimilarDescriptor createSimilarDescriptor = makeCreateSimilarDescriptor(junitPreferences,
            typeToWorkOn);
    final FastCodeContext fastCodeContext = new FastCodeContext(typeToWorkOn, true, junitPreferences);
    final boolean testClassExst = unitTestCU != null && unitTestCU.exists();
    final CreateSimilarDescriptorClass createSimilarDescriptorClass = createSimilarDescriptor
            .getCreateSimilarDescriptorClasses()[0];
    IFile unitTestFile = null;
    boolean createFileAlone = false;
    if (!testClassExst) {
        final String prjURI = testPackageFragment.getResource().getLocationURI().toString();
        final String path = prjURI.substring(prjURI.indexOf(COLON) + 1);
        final File newFileObj = new File(
                path + FORWARD_SLASH + createSimilarDescriptor.getToPattern() + DOT + JAVA_EXTENSION);
        final boolean prjShared = !isEmpty(
                testPackageFragment.getResource().getProject().getPersistentProperties());
        final boolean prjConfigured = !isEmpty(
                isPrjConfigured(testPackageFragment.getResource().getProject().getName()));
        if (versionControlPreferences.isEnable() && prjShared && prjConfigured) {
            final RepositoryService repositoryService = getRepositoryServiceClass();
            if (repositoryService.isFileInRepository(newFileObj)) { // && !MessageDialog.openQuestion(new Shell(), "File present in repository", "File already present in repository. Click yes to overwrite")) {
                /*MessageDialog.openWarning(new Shell(), "File present in repository", junitPreferences.getJunitTestClass() + " is already present in repository. Please synchronise and try again.");
                return null;*/
                createFileAlone = MessageDialog.openQuestion(new Shell(), "File present in repository", "File "
                        + newFileObj.getName()
                        + " already present in repository. Click yes to just create the file, No to return without any action.");
                if (!createFileAlone) {
                    return null;
                }
            }
        } else {
            createFileAlone = true;
        }
        /*final FastCodeCheckinCache checkinCache = FastCodeCheckinCache.getInstance();
        checkinCache.getFilesToCheckIn().add(new FastCodeFileForCheckin(INITIATED, newFileObj.getAbsolutePath()));*/
        addOrUpdateFileStatusInCache(newFileObj);

        createSimilar(fastCodeContext, null, createSimilarDescriptor, new NullProgressMonitor());
        unitTestCU = fastCodeContext.getCompilationUnitRegsistry(createSimilarDescriptorClass);
        if (!createFileAlone) {
            unitTestFile = (IFile) unitTestCU.findPrimaryType().getResource();//.getLocationURI());
            List<FastCodeEntityHolder> chngsForType = commitMessage.get(unitTestFile);
            if (chngsForType == null) {
                chngsForType = new ArrayList<FastCodeEntityHolder>();
                chngsForType.add(new FastCodeEntityHolder(PLACEHOLDER_CLASS,
                        new FastCodeType(unitTestCU.findPrimaryType())));
            }
            commitMessage.put(unitTestFile, chngsForType);
        }

    } else {
        createFileAlone = true;
    }

    if (testClassExst) {
        if (!unitTestCU.getResource().isSynchronized(0)) {
            throw new Exception(
                    unitTestCU.getElementName() + " is not Synchronized, please refresh and try again.");
        }
        unitTestFile = (IFile) unitTestCU.findPrimaryType().getResource(); //.getLocationURI());
    }
    final Map<String, FastCodeMethod> stubMethods = createUnitTestData.getStubMethodsMap(); // FastCodeMethodRegistry.getRegisteredUnitTestStubMethods(junitType);
    if (stubMethods != null) { // && !testClassExst) {
        /*
         * final FastCodeMethodSelectionDialog methodSelectionDialog = new
         * FastCodeMethodSelectionDialog(new Shell(), "Select Methods",
         * "Select One of more Stub Methods from Below", stubMethods, true);
         * methodSelectionDialog.open(); final Object[] regularMethods =
         * methodSelectionDialog.getResult();
         */
        //unitTestFile = (IFile) unitTestCU.findPrimaryType().getResource();
        if (!createFileAlone) {
            final File newFileObj = new File(unitTestFile.getLocationURI().toString());
            final FastCodeCheckinCache checkinCache = FastCodeCheckinCache.getInstance();
            checkinCache.getFilesToCheckIn()
                    .add(new FastCodeFileForCheckin(INITIATED, newFileObj.getAbsolutePath()));
        }
        if (createUnitTestData.getSelectedStubMethodsList() != null) {
            for (final FastCodeMethod fastCodeMethod : createUnitTestData.getSelectedStubMethodsList()
                    .toArray(new FastCodeMethod[0])) {
                createStubMethod(unitTestCU.findPrimaryType(), fastCodeMethod);
                if (!createFileAlone) {
                    List<FastCodeEntityHolder> chngesForType = commitMessage.get(unitTestFile);
                    if (chngesForType == null) {
                        chngesForType = new ArrayList<FastCodeEntityHolder>();
                        final List<Object> fastCodeMethodList = new ArrayList<Object>();
                        fastCodeMethodList.add(fastCodeMethod);
                        chngesForType
                                .add(new FastCodeEntityHolder(PLACEHOLDER_STUBMETHODS, fastCodeMethodList));
                    } else {
                        boolean isNew = true;
                        Object fastCodeMethodList = null;
                        for (final FastCodeEntityHolder fcEntityHolder : chngesForType) {
                            if (fcEntityHolder.getEntityName().equals(PLACEHOLDER_STUBMETHODS)) {
                                fastCodeMethodList = fcEntityHolder.getFastCodeEntity();
                                isNew = false;
                                break;
                            }
                        }

                        if (isNew) {
                            fastCodeMethodList = new ArrayList<Object>();
                            ((List<Object>) fastCodeMethodList).add(fastCodeMethod);
                            chngesForType
                                    .add(new FastCodeEntityHolder(PLACEHOLDER_STUBMETHODS, fastCodeMethodList));
                        } else {
                            ((List<Object>) fastCodeMethodList).add(fastCodeMethod);
                        }
                    }
                    commitMessage.put(unitTestFile, chngesForType);
                }
            }
        }
    }

    if (junitType == JUNIT_TYPE.JUNIT_TYPE_3 || junitType == JUNIT_TYPE.JUNIT_TYPE_CUSTOM) {
        if (junitBaseType != null && junitBaseType.exists()) {
            unitTestCU.createImport(junitBaseType.getFullyQualifiedName(), null, null);
        }
    } else if (junitType == JUNIT_TYPE.JUNIT_TYPE_4) {
        unitTestCU.createImport("org.junit.*", null, null);
        unitTestCU.createImport("org.junit.Assert.*", null, AccStatic, null);
    } else if (junitType == JUNIT_TYPE.JUNIT_TYPE_TESTNG) {
        unitTestCU.createImport("org.testng.annotations.*", null, null);
        unitTestCU.createImport("org.testng.Assert.*", null, AccStatic, null);
    }

    if (unitTestCU == null || !unitTestCU.exists() || createUnitTestData.getClassMethodsSelected() == null
            || methods.length == 0) {
        return unitTestCU != null && unitTestCU.exists() ? unitTestCU.findPrimaryType() : null;
    }

    unitTestCU.createImport(typeToWorkOn.getFullyQualifiedName(), null, null);

    final List<IMethod> retMethods = new ArrayList<IMethod>();
    final UnitTestMethodBuilder methodBuilder = new UnitTestMethodBuilder(fastCodeContext);

    boolean becomeWorkingCopy = false;
    if (!unitTestCU.isWorkingCopy()) {
        becomeWorkingCopy = true;
        unitTestCU.becomeWorkingCopy(null);
    }

    try {
        for (final IMethod method : createUnitTestData.getClassMethodsSelected().toArray(new IMethod[0])) {

            if (EMPTY_STR.equals(createUnitTestData.getTestMethodName())) {
                createUnitTestData.setTestMethodName(method.getElementName());
            }
            IMethod methodToWorkOn = method;
            if (!type.equals(typeToWorkOn)) {
                methodToWorkOn = typeToWorkOn.getMethod(method.getElementName(), method.getParameterTypes());
                if (methodToWorkOn == null || !methodToWorkOn.exists()) {
                    MessageDialog.openError(new Shell(), "Error", "Method " + method.getElementName()
                            + " does not exist in " + typeToWorkOn.getElementName());
                    continue;
                }
            }
            final IMethod[] testMethods = testClassExst
                    ? findTestMethods(typeToWorkOn, methodToWorkOn, junitPreferences)
                    : null;
            // boolean testMethodExist = false, createAotherTestMethod =
            // false;
            // testMethodExist = createAotherTestMethod = false;

            if (testMethods != null && testMethods.length > 0) {
                // testMethodExist = createAotherTestMethod = true;
                /*
                 * final String[] choices = {"Create an additional test",
                 * "Do Nothing", "Jump To The Test"};
                 *
                 * final String choice = getChoiceFromMultipleValues(new
                 * Shell(), "Junit Test Exists for method " +
                 * methodToWorkOn.getElementName(), "Would You Like To",
                 * choices); final int result = findInStringArray(choice,
                 * choices);
                 */

                if (createUnitTestData.getUnitTestChoice().equals(UNIT_TEST_CHOICE.CREATEADDITIONALTEST)) {
                    // break;
                } else if (createUnitTestData.getUnitTestChoice().equals(UNIT_TEST_CHOICE.JUMPTOTEST)) {
                    if (methods.length == 1) {
                        if (testMethods.length == 1) {
                            return testMethods[0];
                        }
                        final MethodSelectionDialog methodSelectionDialog = new MethodSelectionDialog(
                                new Shell(), "Select Test Method",
                                "Multiple tests found for the method you selected, "
                                        + "please select one from the list below.",
                                testMethods, false);
                        methodSelectionDialog.open();
                        return methodSelectionDialog.getResult() == null
                                || methodSelectionDialog.getResult().length == 0 ? null
                                        : (IMethod) methodSelectionDialog.getFirstResult();
                    }
                }
                /*
                 * switch (result) { case 0: // createAotherTestMethod =
                 * true; break; case 1: continue; case 2:
                 *
                 * }
                 */

                // if (createAotherTestMethod) {
                // final MessageDialogWithToggle dialogForMethodBody =
                // openYesNoQuestion(new Shell(),
                // "Create Method Body", "Do you create method body?",
                // "Remember Decision", false,
                // Activator.getDefault().getPreferenceStore(),
                // P_JUNIT_TEST_ASK_FOR_METHOD_BODY);
                // if (dialogForMethodBody.getReturnCode() !=
                // MESSAGE_DIALOG_RETURN_YES) {
                // createMethodBody = false;
                // alwaysCreateTryCatch = false;
                // }
                // }
            }

            if (junitBaseType != null) {
                for (final IMethod meth : junitBaseType.getMethods()) {
                    if (isAbstract(meth.getFlags())) {
                        // add methods here.
                        // copyMethods(junitBaseType,
                        // testCU.findPrimaryType(), meth, null,
                        // METHOD_PATTERN_DEFAULT, null,
                        // RETURN_TYPE.RETURN_TYPE_PASS_THRU, null, null,
                        // false, null, false, false, null, null, null);
                    }
                }
            }

            // if (junitPreferences.isCreateInstance()) {
            // final IField field =
            // testCU.findPrimaryType().getField(instance);
            // if (field == null || !field.exists()) {
            // testCU.findPrimaryType().createField("protected " +
            // type.getElementName() + SPACE + instance + ";\n", null,
            // false, null);
            // }
            // }
            // if (!testMethodExist || createAotherTestMethod) {
            // copyImports(type.getCompilationUnit(), testCU, method);
            // copyMethods(type, testCU.findPrimaryType(), method, instance,
            // junitPreferences.getJunitTestMethod(),
            // createAotherTestMethod ? EXTENSION_OTHER : null,
            // RETURN_TYPE.RETURN_TYPE_CONSUME, null, null, false, "result",
            // createMethodBody, alwaysCreateTryCatch,
            // methodAnnotations, null, null);
            // }

            /**
             * if (method == null) { for (final IMethod meth:
             * testCU.findPrimaryType().getMethods()) { if
             * (!meth.isConstructor()) { testMethod = meth; break; } } }
             * else { String testMethName =
             * replacePlaceHolder(junitPreferences.getJunitTestMethod(),
             * "method_name", method.getElementName()); if
             * (!junitPreferences
             * .getJunitTestMethod().startsWith("${method_name}")) {
             * testMethName =
             * replacePlaceHolder(junitPreferences.getJunitTestMethod(),
             * "method_name",
             * createEmbeddedInstance(method.getElementName())); }
             *
             * testMethod = testCU.findPrimaryType().getMethod(testMethName
             * + (createAotherTestMethod ? EXTENSION_OTHER : EMPTY_STR),
             * null); }
             */
            if (!createFileAlone) {
                final File newFileObj = new File(unitTestFile.getLocationURI().toString());
                final FastCodeCheckinCache checkinCache = FastCodeCheckinCache.getInstance();
                checkinCache.getFilesToCheckIn()
                        .add(new FastCodeFileForCheckin(INITIATED, newFileObj.getAbsolutePath()));
            }
            final IMethod tstMethod = methodBuilder.buildMethod(methodToWorkOn, unitTestCU.findPrimaryType(),
                    createSimilarDescriptor, createSimilarDescriptorClass);
            createUnitTestData.setTestMethodName(EMPTY_STR);
            if (tstMethod != null) {
                retMethods.add(tstMethod);
                if (!createFileAlone) {
                    List<FastCodeEntityHolder> chngesForType = commitMessage.get(unitTestFile);
                    if (chngesForType == null) {
                        chngesForType = new ArrayList<FastCodeEntityHolder>();
                        final List<Object> fastCodeMethodList = new ArrayList<Object>();
                        fastCodeMethodList.add(new FastCodeMethod(tstMethod));
                        chngesForType
                                .add(new FastCodeEntityHolder(PLACEHOLDER_TESTMETHODS, fastCodeMethodList));
                    } else {

                        boolean isNew = true;
                        Object fastCodeMethodList = null;
                        for (final FastCodeEntityHolder fcEntityHolder : chngesForType) {
                            if (fcEntityHolder.getEntityName().equals(PLACEHOLDER_TESTMETHODS)) {
                                fastCodeMethodList = fcEntityHolder.getFastCodeEntity();
                                isNew = false;
                                break;
                            }
                        }

                        if (isNew) {
                            fastCodeMethodList = new ArrayList<Object>();
                            ((List<Object>) fastCodeMethodList).add(new FastCodeMethod(tstMethod));
                            chngesForType
                                    .add(new FastCodeEntityHolder(PLACEHOLDER_TESTMETHODS, fastCodeMethodList));
                        } else {
                            ((List<Object>) fastCodeMethodList).add(new FastCodeMethod(tstMethod));
                        }
                    }
                    commitMessage.put(unitTestFile, chngesForType);
                }
            }
        }
    } catch (final Exception ex) {
        ex.printStackTrace();
        throw new Exception(ex.getMessage(), ex);
    } finally {
        // if (testClassExst) {
        if (!unitTestCU.hasResourceChanged()) {
            unitTestCU.commitWorkingCopy(false, null);
        }
        if (becomeWorkingCopy) {
            unitTestCU.discardWorkingCopy();
        }
    }

    if (retMethods.isEmpty()) {
        return unitTestCU.findPrimaryType();
    } else if (retMethods.size() == 1) {
        return retMethods.get(0);
    } else {
        final IMember[] selectedMembers = getSelectedMembers(IJavaElement.METHOD,
                retMethods.toArray(new IMethod[0]), "Unit Test to Jump", false);
        return selectedMembers == null || selectedMembers.length == 0 ? retMethods.get(0)
                : (IMethod) selectedMembers[0];
    }
}

From source file:org.fastcode.util.SourceUtil.java

License:Open Source License

/**
 * @param fastCodeContext//w ww.j ava2s.co  m
 * @param member
 * @param createSimilarDescriptor
 * @param monitor
 * @return
 * @throws Exception
 */
public static void createSimilar(final FastCodeContext fastCodeContext, final IMember[] members,
        final CreateSimilarDescriptor createSimilarDescriptor, final IProgressMonitor monitor)
        throws Exception {

    final GlobalSettings globalSettings = getInstance();
    final Shell parentShell = MessageUtil.getParentShell();
    final Shell shell = parentShell == null ? new Shell() : parentShell;

    IPackageFragmentRoot packageFragmentRoot = null;
    String newpkg = EMPTY_STR, newcls = EMPTY_STR;
    String targetProject = null;
    final CreateSimilarDescriptorClass[] descriptorClasses = createSimilarDescriptor
            .getCreateSimilarDescUserChoice() == null
                    ? createSimilarDescriptor.getCreateSimilarDescriptorClasses()
                    : createSimilarDescriptor.getCreateSimilarDescUserChoice();
    for (final CreateSimilarDescriptorClass createSimilarDescriptorClass : descriptorClasses) {

        if (createSimilarDescriptorClass == null) {
            continue;
        }
        final boolean replaceName = createSimilarDescriptor.isReplaceName();
        String toName = createSimilarDescriptorClass.getToPattern();

        // final String classBody =
        // createSimilarDescriptorClass.getClassBody();
        IPackageFragment packageFragment = null;

        if (packageFragmentRoot == null) {
            targetProject = createSimilarDescriptorClass.getProject();
            if (fastCodeContext.getFromType() == null) {

                /*final IJavaProject project = getJavaProject(targetProject);
                if (project != null && project.exists() && !isEmpty(createSimilarDescriptorClass.getPackge())) {
                   for (final IPackageFragmentRoot pkgFragmntRoot : project.getPackageFragmentRoots()) {
                      packageFragment = pkgFragmntRoot.getPackageFragment(createSimilarDescriptorClass.getPackge());
                      if (packageFragment != null && packageFragment.exists()) {
                packageFragmentRoot = pkgFragmntRoot;
                break;
                      }
                   }
                }
                if (packageFragment == null || !packageFragment.exists()) {
                   final SelectionDialog packageDialog = JavaUI.createPackageDialog(shell, project, 0, null);
                   if (packageDialog.open() == CANCEL) {
                      return;
                   }
                   packageFragment = (IPackageFragment) packageDialog.getResult()[0];
                   packageFragmentRoot = (IPackageFragmentRoot) packageFragment.getParent();
                } else if (isEmpty(createSimilarDescriptorClass.getSubPackage()) && packageFragment.hasSubpackages()) {
                   final List<IPackageFragment> subPackages = new ArrayList<IPackageFragment>();
                   for (final IJavaElement chldPkgFragment : packageFragmentRoot.getChildren()) {
                      if (chldPkgFragment instanceof IPackageFragment
                   && chldPkgFragment.getElementName().startsWith(packageFragment.getElementName())) {
                subPackages.add((IPackageFragment) chldPkgFragment);
                      }
                   }
                   if (!subPackages.isEmpty()) {
                      final PackageSelectionDialog selectionDialog = new PackageSelectionDialog(shell, "Sub Package",
                   "Choose the sub pacage from below", subPackages.toArray(new IPackageFragment[0]));
                      if (selectionDialog.open() != CANCEL) {
                packageFragment = (IPackageFragment) selectionDialog.getFirstResult();
                      }
                   }
                }*/

                packageFragment = createSimilarDescriptorClass.getUserInputPackage();
                packageFragmentRoot = (IPackageFragmentRoot) packageFragment.getParent();
                newpkg = packageFragment.getElementName();
                newcls = replacePlaceHolders(toName, fastCodeContext.getPlaceHolders());
            } else {
                if (fastCodeContext.isUnitTest()) {
                    String sourcePath = globalSettings.isUseDefaultForPath()
                            ? globalSettings.getSourcePathTest()
                            : createSimilarDescriptorClass.getSourcePath();
                    sourcePath = getDefaultPathFromProject(fastCodeContext.getFromType().getJavaProject(),
                            "test", sourcePath);
                    packageFragmentRoot = getPackageRootFromProject(
                            fastCodeContext.getFromType().getJavaProject(), sourcePath);
                } else if (!isEmpty(targetProject)) {
                    final String sourcePath = globalSettings.isUseDefaultForPath()
                            ? getPathFromGlobalSettings(
                                    fastCodeContext.getFromType().getJavaProject().getElementName())
                            : createSimilarDescriptorClass.getSourcePath();
                    ;
                    packageFragmentRoot = getPackageRootFromProject(createSimilarDescriptorClass.getProject(),
                            sourcePath);
                } else {
                    packageFragmentRoot = (IPackageFragmentRoot) fastCodeContext.getFromType()
                            .getPackageFragment().getParent();
                    targetProject = packageFragmentRoot.getParent().getElementName();
                }
                final String fullname = fastCodeContext.getFromType().getFullyQualifiedName();
                final String fromPattern = createSimilarDescriptor.getFromPattern();
                if (fromPattern != null) {
                    parseTokens(fromPattern, fullname, fastCodeContext.getPlaceHolders());
                }
                if (packageFragmentRoot == null || !packageFragmentRoot.exists()) {
                    throw new Exception("Unable to find source path for, please check configuration.");
                }
                toName = replacePlaceHolders(toName, fastCodeContext.getPlaceHolders());
                if (createSimilarDescriptor.isDifferentName()) {
                    toName = fullname.replaceAll(createSimilarDescriptor.getReplacePart(),
                            createSimilarDescriptor.getReplaceValue());
                }
                final int lastDotPos = toName.lastIndexOf(DOT_CHAR);
                newpkg = lastDotPos != -1 ? toName.substring(0, lastDotPos)
                        : fastCodeContext.getFromType().getPackageFragment().getElementName();
                newcls = lastDotPos != -1 ? toName.substring(lastDotPos + 1) : toName;
                packageFragment = packageFragmentRoot.getPackageFragment(newpkg);
            }
        }

        if (packageFragmentRoot == null || !packageFragmentRoot.exists()) {
            throw new Exception("Unable to find package fragment root for " + toName);
        }

        // fastCodeContext.addToPlaceHolders(toName, newcls);
        final boolean isImplClass = createSimilarDescriptorClass.getParentDescriptor() != null
                && createSimilarDescriptorClass
                        .getRelationTypeToParent() == RELATION_TYPE.RELATION_TYPE_IMPLEMENTS;

        if (isImplClass) {
            newcls += globalSettings.getImplExtension();
            if (!isEmpty(createSimilarDescriptorClass.getSubPackage())) {
                newpkg += "." + createSimilarDescriptorClass.getSubPackage();
                packageFragment = packageFragmentRoot.getPackageFragment(newpkg);
                if (packageFragment == null || !packageFragment.exists()) {
                    packageFragment = packageFragmentRoot.createPackageFragment(newpkg, false, monitor);
                }
            }
        }

        fastCodeContext.addToPlaceHolders(PACKAGE_NAME_STR, newpkg);
        fastCodeContext.addToPlaceHolders(CLASS_NAME_STR, newcls);
        if (createSimilarDescriptorClass.isFinalClass()) {
            fastCodeContext.addToPlaceHolders(CLASS_MODIFIER_STR, "final");
        }
        fastCodeContext.addToPlaceHolders(CLASS_INSTANCE_STR, createDefaultInstance(newcls));
        fastCodeContext.addToPlaceHolders(CLASS_TYPE_STR,
                createSimilarDescriptorClass.getClassType().value().toLowerCase());

        if (!fastCodeContext.getPlaceHolders().containsKey(KEYWORD_FROM_CLASS)
                && fastCodeContext.getFromType() != null) {
            fastCodeContext.addToPlaceHolders(KEYWORD_FROM_CLASS,
                    fastCodeContext.getFromType().getElementName());
            fastCodeContext.addToPlaceHolders(KEYWORD_FROM_INSTANCE,
                    createDefaultInstance(fastCodeContext.getFromType().getElementName()));
        }

        if (!fastCodeContext.getPlaceHolders().containsKey(KEYWORD_TO_CLASS)) {
            fastCodeContext.addToPlaceHolders(KEYWORD_TO_CLASS, newcls);
            fastCodeContext.addToPlaceHolders(KEYWORD_TO_PACKAGE, newpkg);
            fastCodeContext.addToPlaceHolders(KEYWORD_TO_FULL_CLASS, newpkg + DOT + newcls);
            fastCodeContext.addToPlaceHolders(KEYWORD_TO_INSTANCE, createDefaultInstance(newcls));
        } else if (isImplClass) {
            fastCodeContext.addToPlaceHolders(KEYWORD_TO_IMPL_PACKAGE, newpkg);
            fastCodeContext.addToPlaceHolders(KEYWORD_TO_IMPL_CLASS, newcls);
            fastCodeContext.addToPlaceHolders(KEYWORD_TO_FULL_IMPL_CLASS, newpkg + DOT + newcls);
        }

        if (replaceName && (packageFragment == null || !packageFragment.exists())) {
            throw new Exception("Fatal error : package must exist.");
        } else if (packageFragment == null || !packageFragment.exists()) {
            final File pkgObj = new File(packageFragmentRoot.getResource().getLocationURI());
            /*final FastCodeCheckinCache checkinCache = FastCodeCheckinCache.getInstance();
            checkinCache.getFilesToCheckIn().add(new FastCodeFileForCheckin(INITIATED, pkgObj.getAbsolutePath()));*/
            addOrUpdateFileStatusInCache(pkgObj);

            packageFragment = packageFragmentRoot.createPackageFragment(newpkg, false, monitor);
        }

        ICompilationUnit compilationUnit = packageFragment.getCompilationUnit(newcls + DOT + JAVA_EXTENSION);
        boolean isNew = false;
        final CompUnitBuilder compUnitBuilder = new SimilarCompUnitBuilder();
        if (compilationUnit == null || !compilationUnit.exists()) {
            fastCodeConsole.writeToConsole("Creating class " + newcls);
            // compilationUnit = createCompUnit(packageFragment,
            // fastCodeContext, createSimilarDescriptorClass, newcls);
            final String prjURI = packageFragment.getResource().getLocationURI().toString();
            final String path = prjURI.substring(prjURI.indexOf(COLON) + 1);
            final File newFileObj = new File(path + FORWARD_SLASH + newcls + DOT + JAVA_EXTENSION);
            final FastCodeCheckinCache checkinCache = FastCodeCheckinCache.getInstance();
            checkinCache.getFilesToCheckIn()
                    .add(new FastCodeFileForCheckin(INITIATED, newFileObj.getAbsolutePath()));

            compilationUnit = compUnitBuilder.buildCompUnit(packageFragment, fastCodeContext,
                    createSimilarDescriptorClass, newcls, fastCodeConsole);
            isNew = true;
        } else {
            if (!compilationUnit.getResource().isSynchronized(0)) {
                throw new Exception(compilationUnit.getElementName()
                        + " is not Synchronized, please refresh and try again.");
            }
            fastCodeConsole.writeToConsole("Class  " + newcls + " exists already.");
        }
        fastCodeContext.addCompilationUnitToRegsistry(createSimilarDescriptorClass, compilationUnit);

        compilationUnit.becomeWorkingCopy(monitor);
        fastCodeContext.addResource(new FastCodeResource(compilationUnit.getResource(), isNew));

        monitor.subTask("Creating details for " + compilationUnit.findPrimaryType().getFullyQualifiedName());

        try {
            IType pType = compilationUnit.findPrimaryType();
            int tries = 0;
            // hack because findPrimaryType is not available immediately
            // sometimes.
            while (isNew && (tries++ < MAX_TRY || pType == null || !pType.exists())) {
                pType = compilationUnit.findPrimaryType();
                Thread.sleep(100);
            }
            if (pType == null || !pType.exists()) {
                throw new Exception("Unknown exception occured, please try it again.");
            }

            createNewTypeDetails(fastCodeContext, pType, members, createSimilarDescriptor,
                    createSimilarDescriptorClass, monitor);
            if (globalSettings.isAutoSave()) {
                compilationUnit.commitWorkingCopy(false, monitor);
            }
        } finally {
            compilationUnit.discardWorkingCopy();
        }
    }

    // monitor.subTask("Creating configuration for " +
    // cu.findPrimaryType().getFullyQualifiedName());

    boolean createConfig = false;
    if (createSimilarDescriptor.getNoOfInputs() > 1) {
        return;
    }
    for (final CreateSimilarDescriptorConfig descriptorConfig : createSimilarDescriptor
            .getDescriptorConfigParts()) {
        if (descriptorConfig != null) {
            createConfig = true;
        }
    }

    if (!createConfig) {
        return;
    }

    boolean showFieldsDialog = true;
    final List<FastCodeField> fastCodeFields = new ArrayList<FastCodeField>();
    final Map<String, List<FastCodeField>> fieldsMap = new HashMap<String, List<FastCodeField>>();
    fieldsMap.put("fields", fastCodeFields);

    IType typeForConfiguration = null;
    for (final CreateSimilarDescriptorClass createSimilarDescriptorClass : descriptorClasses) {
        final ICompilationUnit compilationUnit = fastCodeContext
                .getCompilationUnitRegsistry(createSimilarDescriptorClass);
        if (compilationUnit.findPrimaryType().isClass()) {
            typeForConfiguration = compilationUnit.findPrimaryType();
            break;
        }
    }

    for (final CreateSimilarDescriptorConfig descriptorConfig : createSimilarDescriptor
            .getDescriptorConfigParts()) {

        if (descriptorConfig == null) {
            continue;
        }

        final IField[] fields = getFieldsOfType(typeForConfiguration);
        if (showFieldsDialog && fields != null && fields.length > 0) {
            final FieldSelectionDialog fieldSelectionDialog = new FieldSelectionDialog(shell,
                    "Fields for configuration",
                    "Choose the fields for configuration " + descriptorConfig.getConfigType(), fields, true);

            if (fieldSelectionDialog.open() != CANCEL) {
                final Object[] results = fieldSelectionDialog.getResult();
                for (final Object result : results) {
                    final IField field = (IField) result;
                    fastCodeFields.add(new FastCodeField(field, field.getElementName()));
                }
                showFieldsDialog = false; // get the fields first time.
            }
        }

        // String fileName = descriptorConfig.getConfigFileName();
        // final String fileName =
        // replacePlaceHolders(descriptorConfig.getConfigFileName(),
        // fastCodeContext.getPlaceHolders());

        createConfigurations(fastCodeContext, descriptorConfig, targetProject, fieldsMap);
    }
}