Example usage for org.eclipse.jdt.core ICompilationUnit hasResourceChanged

List of usage examples for org.eclipse.jdt.core ICompilationUnit hasResourceChanged

Introduction

In this page you can find the example usage for org.eclipse.jdt.core ICompilationUnit hasResourceChanged.

Prototype

public boolean hasResourceChanged();

Source Link

Document

Returns whether the resource of this working copy has changed since the inception of this working copy.

Usage

From source file:edu.brown.cs.bubbles.bedrock.BedrockEditor.java

License:Open Source License

/********************************************************************************/

private synchronized FileData findFile(String proj, String file, String bid, String id)
        throws BedrockException {
    FileData fd = file_map.get(file);/* www  . j  a v  a  2s.c  om*/

    if (fd == null) {
        ICompilationUnit icu = null;
        icu = our_plugin.getProjectManager().getCompilationUnit(proj, file);
        if (icu == null && proj != null) {
            icu = our_plugin.getProjectManager().getCompilationUnit(null, file);
            if (icu != null)
                proj = null;
        }

        if (icu == null)
            return null;
        BedrockPlugin.logD("START FILE " + proj + " " + file + " " + bid + " " + icu.isWorkingCopy() + " "
                + icu.hasResourceChanged() + " " + icu.isOpen() + " " + icu.getOwner() + " "
                + System.identityHashCode(icu) + " " + System.identityHashCode(icu.getPrimary()));

        icu = icu.getPrimary();

        fd = new FileData(proj, file, icu);
        file_map.put(file, fd);
    }

    if (id != null)
        fd.setCurrentId(bid, id);

    return fd;
}

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

License:Open Source License

/**
 *
 * @param typeToWorkOn/*  w w  w .j ava  2 s .co 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];
    }
}