/** * Ensures that creating a DOM AST and computing the bindings takes the owner's working copies * into account. (regression test for bug 39533 Working copy with no corresponding file not * considered by NameLookup) * * @deprecated using deprecated code */ public void testParseCompilationUnit1() throws CoreException { ICompilationUnit workingCopy1 = null; ICompilationUnit workingCopy2 = null; try { TestWorkingCopyOwner owner = new TestWorkingCopyOwner(); workingCopy1 = getCompilationUnit("P/X.java").getWorkingCopy(owner, null); workingCopy1.getBuffer().setContents("public class X implements I {\n" + "}"); workingCopy1.makeConsistent(null); workingCopy2 = getCompilationUnit("P/I.java").getWorkingCopy(owner, null); workingCopy2.getBuffer().setContents("public interface I {\n" + "}"); workingCopy2.makeConsistent(null); ASTParser parser = ASTParser.newParser(AST.JLS2); parser.setSource(workingCopy1); parser.setResolveBindings(true); parser.setWorkingCopyOwner(owner); CompilationUnit cu = (CompilationUnit) parser.createAST(null); List types = cu.types(); assertEquals("Unexpected number of types in AST", 1, types.size()); TypeDeclaration type = (TypeDeclaration) types.get(0); ITypeBinding typeBinding = type.resolveBinding(); assertTypeBindingsEqual("Unexpected interfaces", "I", typeBinding.getInterfaces()); } finally { if (workingCopy1 != null) { workingCopy1.discardWorkingCopy(); } if (workingCopy2 != null) { workingCopy2.discardWorkingCopy(); } } }
/** * Gets the problems for a given src file. * * @param src The src file. * @param ids Array of problem ids to accept. * @return The problems. */ public static IProblem[] getProblems(ICompilationUnit src, int[] ids) throws Exception { ICompilationUnit workingCopy = src.getWorkingCopy(null); ProblemRequestor requestor = new ProblemRequestor(ids); try { workingCopy.discardWorkingCopy(); workingCopy.becomeWorkingCopy(requestor, null); } finally { workingCopy.discardWorkingCopy(); } List<IProblem> problems = requestor.getProblems(); return (IProblem[]) problems.toArray(new IProblem[problems.size()]); }
/* * Tests that a primary working copy is back in compilation unit mode when discardWorkingCopy() is called. */ public void testDiscardWorkingCopy1() throws CoreException { ICompilationUnit cu = null; try { cu = getCompilationUnit("P/X.java"); cu.becomeWorkingCopy(null); assertTrue("should be in working copy mode", cu.isWorkingCopy()); cu.discardWorkingCopy(); assertTrue("should no longer be in working copy mode", !cu.isWorkingCopy()); } finally { if (cu != null) { cu.discardWorkingCopy(); } } }
public MClassJDT(MPackageJDT mpkg, String name) { String fullname = "???." + name; ICompilationUnit workingCopy = null; try { IPackageFragment jdtPackage = (IPackageFragment) mpkg.getJdtPackageInfo().getParent(); fullname = jdtPackage.getElementName() + "." + name; if (jdtPackage.getCompilationUnit(name + ".java").exists()) throw new MyRuntimeException("Class with name '" + fullname + "' already exists."); IProgressMonitor monitor = MyMonitor.currentMonitor(); String content = "public class " + name + " {}"; ICompilationUnit cu = jdtPackage.createCompilationUnit(name + ".java", content, true, null); workingCopy = cu.getWorkingCopy(monitor); workingCopy.createPackageDeclaration(jdtPackage.getElementName(), monitor); String source = ((IOpenable) workingCopy).getBuffer().getContents(); Map<?, ?> options = EclipseUtils.getJdtCorePreferences(jdtPackage); // instantiate the default code formatter with the given options final CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(options, ToolFactory.M_FORMAT_NEW); TextEdit edit = codeFormatter.format( CodeFormatter.K_COMPILATION_UNIT, source, 0, source.length(), 0, null); if (edit == null) { throw new MyRuntimeException("Can't format the source: " + source); } workingCopy.applyTextEdit(edit, monitor); workingCopy.commitWorkingCopy(false, monitor); workingCopy.discardWorkingCopy(); jdtCu = jdtPackage.getCompilationUnit(name + ".java"); } catch (JavaModelException e) { throw new MyRuntimeException("Can not create '" + fullname + "' class.", e); } finally { if (workingCopy != null) try { workingCopy.discardWorkingCopy(); } catch (JavaModelException e) { throw new MyRuntimeException(e); } } }
/* * Tests that a primary working copy is removed from its parent after it is discarded and * there is no underlying resource. */ public void testDiscardWorkingCopy5() throws CoreException { ICompilationUnit cu = null; try { cu = getCompilationUnit("P/Y.java"); cu.becomeWorkingCopy(null); cu.discardWorkingCopy(); assertElementsEqual( "Unexpected children of default package", "X.java [in <default> [in <project root> [in P]]]", getPackage("/P").getChildren()); } finally { if (cu != null) { cu.discardWorkingCopy(); } } }
/* * Ensures that getWorkingCopy(WorkingCopyOwner, IProblemRequestor, IProgressMonitor) * returns a different working copy if called twice with a different working copy owner. */ public void testGetWorkingCopy2() throws CoreException { ICompilationUnit workingCopy1 = null; ICompilationUnit workingCopy2 = null; try { ICompilationUnit cu = getCompilationUnit("P/X.java"); TestWorkingCopyOwner owner1 = new TestWorkingCopyOwner(); workingCopy1 = cu.getWorkingCopy(owner1, null); TestWorkingCopyOwner owner2 = new TestWorkingCopyOwner(); workingCopy2 = cu.getWorkingCopy(owner2, null); assertTrue("working copies should be different", !workingCopy1.equals(workingCopy2)); } finally { if (workingCopy1 != null) { workingCopy1.discardWorkingCopy(); } if (workingCopy2 != null) { workingCopy2.discardWorkingCopy(); } } }
/* * Ensures that getCorrespondingResource() returns a non-null value for a primary working copy. * (regression test for bug 44065 NPE during hot code replace) */ public void testGetCorrespondingResource() throws CoreException { ICompilationUnit cu = null; try { cu = getCompilationUnit("P/X.java"); cu.becomeWorkingCopy(null); assertResourceNamesEqual( "Unexpected resource", "X.java", new Object[] {cu.getCorrespondingResource()}); } finally { if (cu != null) { cu.discardWorkingCopy(); } } }
// non-optional errors cannot be ignored public void test004() throws CoreException { ICompilationUnit unit = null; try { IJavaProject project = createJavaProject("P", new String[] {}, new String[] {"JCL_LIB"}, "bin"); project.setOption(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR); IClasspathEntry[] originalCP = project.getRawClasspath(); IClasspathEntry[] newCP = new IClasspathEntry[originalCP.length + 1]; System.arraycopy(originalCP, 0, newCP, 0, originalCP.length); newCP[originalCP.length] = JavaCore.newSourceEntry( new Path("/P/src"), null, null, null, new IClasspathAttribute[] {ATTR_IGNORE_OPTIONAL_PROBLEMS_TRUE}); project.setRawClasspath(newCP, null); createFolder("/P/src/p"); IFile file = createFile( "/P/src/p/X.java", "package p;\n" + "public class X {\n" + " public void foo() {\n" + " int i;\n" + " }\n" + " public void bar() {\n" + " a++;\n" + " }\n" + "}"); unit = (ICompilationUnit) JavaCore.create(file); ProblemRequestor problemRequestor = new ProblemRequestor(); WorkingCopyOwner owner = newWorkingCopyOwner(problemRequestor); unit.getWorkingCopy(owner, null); assertProblems( "Unexpeted problems", "----------\n" + "1. ERROR in /P/src/p/X.java\n" + "a cannot be resolved to a variable\n" + "----------\n", problemRequestor); } finally { if (unit != null) { unit.discardWorkingCopy(); } deleteProject("P"); } }
/* * Ensures that searching takes the primary owner's working copies and the given working copies into account. * (regression test for bug 43300 SearchEngine(IWorkingCopy[] workingCopies) not backward compatible) */ public void testSearch4() throws CoreException { ICompilationUnit primaryWorkingCopy = null; try { createFolder("P/p"); createFile("/P/p/Y.java", ""); primaryWorkingCopy = getCompilationUnit("P/p/Y.java"); primaryWorkingCopy.becomeWorkingCopy(null); // create type Y in working copy primaryWorkingCopy.getBuffer().setContents("package p;\n" + "public class Y {\n" + "}"); primaryWorkingCopy.makeConsistent(null); // create new working copy on X.java and add type X this.workingCopy = getCompilationUnit("P/p/X.java").getWorkingCopy(null); this.workingCopy.getBuffer().setContents("package p;\n" + "public class X {\n" + "}"); this.workingCopy.makeConsistent(null); JavaSearchTests.JavaSearchResultCollector resultCollector = new JavaSearchTests.JavaSearchResultCollector(); IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] {primaryWorkingCopy.getParent()}); SearchPattern pattern = SearchPattern.createPattern( "*", IJavaSearchConstants.TYPE, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE); new SearchEngine(new ICompilationUnit[] {this.workingCopy}) .search( pattern, new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()}, scope, resultCollector, null); assertEquals("p/X.java p.X [X]\n" + "p/Y.java p.Y [Y]", resultCollector.toString()); } finally { if (primaryWorkingCopy != null) { primaryWorkingCopy.discardWorkingCopy(); } deleteFile("/P/p/Y.java"); } }
/* * Ensures that the correct working copies are returned by JavaCore.getWorkingCopies(WorkingCopyOwner) */ public void testGetWorkingCopies() throws CoreException { ICompilationUnit workingCopy11 = null; ICompilationUnit workingCopy12 = null; ICompilationUnit workingCopy21 = null; try { // initialiy no working copies for this owner TestWorkingCopyOwner owner1 = new TestWorkingCopyOwner(); assertSortedElementsEqual( "Unexpected working copies (1)", "", JavaCore.getWorkingCopies(owner1)); // create working copy on existing cu ICompilationUnit cu1 = getCompilationUnit("P/X.java"); workingCopy11 = cu1.getWorkingCopy(owner1, null); assertSortedElementsEqual( "Unexpected working copies (2)", "[Working copy] X.java [in <default> [in <project root> [in P]]]", JavaCore.getWorkingCopies(owner1)); // create working copy on non-existing cu ICompilationUnit cu2 = getCompilationUnit("P/Y.java"); workingCopy12 = cu2.getWorkingCopy(owner1, null); assertSortedElementsEqual( "Unexpected working copies (3)", "[Working copy] X.java [in <default> [in <project root> [in P]]]\n" + "[Working copy] Y.java [in <default> [in <project root> [in P]]]", JavaCore.getWorkingCopies(owner1)); // create working copy for another owner TestWorkingCopyOwner owner2 = new TestWorkingCopyOwner(); workingCopy21 = cu1.getWorkingCopy(owner2, null); // owner2 should have the new working copy assertSortedElementsEqual( "Unexpected working copies (4)", "[Working copy] X.java [in <default> [in <project root> [in P]]]", JavaCore.getWorkingCopies(owner2)); // owner1 should still have the same working copies assertSortedElementsEqual( "Unexpected working copies (5)", "[Working copy] X.java [in <default> [in <project root> [in P]]]\n" + "[Working copy] Y.java [in <default> [in <project root> [in P]]]", JavaCore.getWorkingCopies(owner1)); // discard first working copy workingCopy11.discardWorkingCopy(); assertSortedElementsEqual( "Unexpected working copies (6)", "[Working copy] Y.java [in <default> [in <project root> [in P]]]", JavaCore.getWorkingCopies(owner1)); } finally { if (workingCopy11 != null) { workingCopy11.discardWorkingCopy(); } if (workingCopy12 != null) { workingCopy12.discardWorkingCopy(); } if (workingCopy21 != null) { workingCopy21.discardWorkingCopy(); } } }
/** * @param insideTagBody * @param tagBody * @param templateTag * @param contextMap * @param placeHolders * @param spacesBeforeCursor * @param overrideMethods * @param exist * @param overWrite * @param type * @throws JavaModelException * @throws Exception */ public void createClassFromTag( final String className, final Object packge, final Object project, String insideTagBody, final Map<String, Object> contextMap, final Map<String, Object> placeHolders, final ICompilationUnit compUnit, final String typeToCreate, final String spacesBeforeCursor, boolean overrideMethods, final boolean exist, final boolean overWrite) throws JavaModelException, Exception { final VersionControlPreferences versionControlPreferences = VersionControlPreferences.getInstance(); if (typeToCreate.equals(ACTION_ENTITY.Innerclass.getValue())) { compUnit.becomeWorkingCopy(null); final File newFileObj = new File(compUnit.getResource().getLocationURI().toString()); /*final FastCodeCheckinCache checkinCache = FastCodeCheckinCache.getInstance(); checkinCache.getFilesToCheckIn().add(new FastCodeFileForCheckin(INITIATED, newFileObj.getAbsolutePath()));*/ try { // addOrUpdateFileStatusInCache(newFileObj); final IType innerClassType = SourceUtil.createInnerClass(insideTagBody, compUnit); /*final boolean prjShared = !isEmpty(compUnit.getResource().getProject().getPersistentProperties()); final boolean prjConfigured = !isEmpty(isPrjConfigured(compUnit.getResource().getProject().getName()));*/ if ((Boolean) placeHolders.get(AUTO_CHECKIN)) { if (proceedWithAutoCheckin(newFileObj, compUnit.getResource().getProject())) { final IFile file = (IFile) innerClassType.getResource(); // .getLocationURI()); List<FastCodeEntityHolder> chngsForType = ((Map<Object, List<FastCodeEntityHolder>>) contextMap.get(FC_OBJ_CREATED)) .get(file); if (chngsForType == null) { chngsForType = new ArrayList<FastCodeEntityHolder>(); final List<Object> innerClassList = new ArrayList<Object>(); innerClassList.add(new FastCodeType(innerClassType)); chngsForType.add(new FastCodeEntityHolder(PLACEHOLDER_INNERCLASSES, innerClassList)); } else { boolean isNew = true; Object fastCodeFieldList = null; for (final FastCodeEntityHolder fcEntityHolder : chngsForType) { if (fcEntityHolder.getEntityName().equals(PLACEHOLDER_INNERCLASSES)) { fastCodeFieldList = fcEntityHolder.getFastCodeEntity(); isNew = false; break; } } if (isNew) { fastCodeFieldList = new ArrayList<Object>(); ((List<Object>) fastCodeFieldList).add(innerClassType); chngsForType.add( new FastCodeEntityHolder(PLACEHOLDER_INNERCLASSES, fastCodeFieldList)); } else { ((List<Object>) fastCodeFieldList).add(innerClassType); } /*Object innerClassList = chngsForType.get("innerClasses"); if (innerClassList == null) { innerClassList = new ArrayList<Object>(); } ((List<Object>) innerClassList).add(new FastCodeType(innerClassType)); chngsForType.put("innerClasses", innerClassList);*/ } ((Map<Object, List<FastCodeEntityHolder>>) contextMap.get(FC_OBJ_CREATED)) .put(file, chngsForType); } } } catch (final FastCodeRepositoryException ex) { ex.printStackTrace(); } compUnit.commitWorkingCopy(false, null); compUnit.discardWorkingCopy(); return; } final IJavaProject prj = project instanceof String ? getJavaProject((String) project) : (IJavaProject) project; /*IJavaProject prj = getJavaProject(project);// getJavaProject(attributes.get(PLACEHOLDER_PROJECT)); if (prj == null) { prj = getJavaProject(placeHolders.get(PLACEHOLDER_PROJECT) instanceof FastCodeProject ? ((FastCodeProject) placeHolders .get(PLACEHOLDER_PROJECT)).getName() : (String) placeHolders.get(PLACEHOLDER_PROJECT)); } if (prj == null) { prj = this.javaProject = this.javaProject == null ? getWorkingJavaProjectFromUser() : this.javaProject;//did for j2ee base }*/ if (prj == null) { throw new Exception("Can not continue without java project."); } final String srcPath = typeToCreate.equals(ACTION_ENTITY.Test.getValue()) ? getDefaultPathFromProject(prj, typeToCreate, EMPTY_STR) : getDefaultPathFromProject(prj, "source", EMPTY_STR); IPackageFragment pkgFrgmt = null; final TemplateTagsProcessor templateTagsProcessor = new TemplateTagsProcessor(); if (packge instanceof String && !isEmpty((String) packge) || packge instanceof IPackageFragment) { pkgFrgmt = packge instanceof String ? templateTagsProcessor.getPackageFragment( prj, srcPath, (String) packge, typeToCreate.equals(ACTION_ENTITY.Test.getValue()) ? typeToCreate : "source") : (IPackageFragment) packge; } if (pkgFrgmt == null) { /*final boolean prjShared = !isEmpty(prj.getProject().getPersistentProperties()); final boolean prjConfigured = !isEmpty(isPrjConfigured(prj.getProject().getName()));*/ File file = null; if ((Boolean) placeHolders.get(AUTO_CHECKIN)) { if (proceedWithAutoCheckin(file, prj.getProject())) { final String prjURI = prj.getResource().getLocationURI().toString(); final String path = prjURI.substring(prjURI.indexOf(COLON) + 1); final String newPackURL = path + srcPath + FILE_SEPARATOR + ((String) packge).replace(DOT, FILE_SEPARATOR); file = new File(newPackURL); // final FastCodeCheckinCache checkinCache = FastCodeCheckinCache.getInstance(); addOrUpdateFileStatusInCache(file); // checkinCache.getFilesToCheckIn().add(new FastCodeFileForCheckin(INITIATED, // file.getAbsolutePath())); } } pkgFrgmt = templateTagsProcessor.createPackage( prj, (String) packge, typeToCreate, contextMap); // createPackage(prj, // attributes.get(PLACEHOLDER_PACKAGE)); if ((Boolean) placeHolders.get(AUTO_CHECKIN)) { if (proceedWithAutoCheckin(null, prj.getProject())) { final IFile ifile = getIFileFromFile(file); List<FastCodeEntityHolder> chngsForType = ((Map<Object, List<FastCodeEntityHolder>>) contextMap.get(FC_OBJ_CREATED)).get(ifile); if (chngsForType == null) { chngsForType = new ArrayList<FastCodeEntityHolder>(); chngsForType.add( new FastCodeEntityHolder(PLACEHOLDER_PACKAGE, new FastCodePackage(pkgFrgmt))); } ((Map<Object, List<FastCodeEntityHolder>>) contextMap.get(FC_OBJ_CREATED)) .put(ifile, chngsForType); } } } boolean createFileAlone = true; if ((Boolean) placeHolders.get(AUTO_CHECKIN)) { String path; try { final boolean prjShared = !isEmpty(pkgFrgmt.getResource().getProject().getPersistentProperties()); final boolean prjConfigured = !isEmpty(isPrjConfigured(pkgFrgmt.getResource().getProject().getName())); createFileAlone = !(versionControlPreferences.isEnable() && prjShared && prjConfigured); final String prjURI = pkgFrgmt.getResource().getLocationURI().toString(); path = prjURI.substring(prjURI.indexOf(COLON) + 1); final File newFileObj = new File(path + FORWARD_SLASH + className + DOT + JAVA_EXTENSION); if (versionControlPreferences.isEnable() && prjShared && prjConfigured) { final RepositoryService repositoryService = getRepositoryServiceClass(); try { 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", className + " is already present in repository. Please synchronise and try again."); return;*/ 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; } } } catch (final Throwable th) { th.printStackTrace(); createFileAlone = true; } } final FastCodeCheckinCache checkinCache = FastCodeCheckinCache.getInstance(); checkinCache .getFilesToCheckIn() .add(new FastCodeFileForCheckin(INITIATED, newFileObj.getAbsolutePath())); } catch (final FastCodeRepositoryException ex) { ex.printStackTrace(); } } /*if (parseClassName(insideTagBody) == null) { insideTagBody = MODIFIER_PUBLIC + SPACE + typeToCreate + SPACE + className + SPACE + LEFT_CURL + NEWLINE + insideTagBody + NEWLINE + RIGHT_CURL; }*/ final Object codeFormatter = createCodeFormatter(prj.getProject()); if (!isEmpty(insideTagBody)) { insideTagBody = formatCode(insideTagBody.trim(), codeFormatter); } ICompilationUnit compilationUnit = null; if (exist) { if (overWrite) { final IType type = prj.findType(pkgFrgmt.getElementName() + DOT + className.trim()); if (type.getCompilationUnit().hasUnsavedChanges()) { type.getCompilationUnit().save(new NullProgressMonitor(), true); } // type.getCompilationUnit().delete(true, new NullProgressMonitor()); insideTagBody = buildClass(insideTagBody, pkgFrgmt, prj, className); // type.getCompilationUnit().getBuffer().setContents(insideTagBody); final ReplaceEdit replaceEdit = new ReplaceEdit(0, type.getCompilationUnit().getSource().length(), insideTagBody); type.getCompilationUnit().applyTextEdit(replaceEdit, new NullProgressMonitor()); compilationUnit = type.getCompilationUnit(); compilationUnit.becomeWorkingCopy(null); compilationUnit.commitWorkingCopy(false, null); compilationUnit.discardWorkingCopy(); // refreshProject(prj.getElementName()); } else { return; } } else { compilationUnit = SourceUtil.createClass(insideTagBody, pkgFrgmt, prj, className); } if (compilationUnit == null) { return; } if (!typeToCreate.equals(ACTION_ENTITY.Interface.getValue())) { if (compilationUnit.findPrimaryType().getSuperclassName() != null) { final IType superClassType = prj.findType( getFQNameFromFieldTypeName( compilationUnit.findPrimaryType().getSuperclassName(), compilationUnit)); if (superClassType != null && superClassType.exists()) { if (Flags.isAbstract( superClassType .getFlags()) /*Modifier.isAbstract(Class.forName(superClassType.getFullyQualifiedName()).getModifiers())*/) { overrideMethods = true; } } } if (overrideMethods) { final String superInterfaces[] = compilationUnit.findPrimaryType().getSuperInterfaceNames(); if (superInterfaces != null) { for (final String superInertafce : superInterfaces) { final IType superIntType = prj.findType(getFQNameFromFieldTypeName(superInertafce, compilationUnit)); final FastCodeContext fastCodeContext = new FastCodeContext(superIntType); final CreateSimilarDescriptorClass createSimilarDescriptorClass = new CreateSimilarDescriptorClass.Builder().withClassType(CLASS_TYPE.CLASS).build(); implementInterfaceMethods( superIntType, fastCodeContext, compilationUnit.findPrimaryType(), null, createSimilarDescriptorClass); final IType[] superInterfaceType = getSuperInterfacesType(superIntType); if (superInterfaceType != null) { for (final IType type : superInterfaceType) { if (type == null || !type.exists()) { continue; } final FastCodeContext context = new FastCodeContext(type); implementInterfaceMethods( type, context, compilationUnit.findPrimaryType(), null, createSimilarDescriptorClass); } } } } overrideBaseClassMethods(compilationUnit); } } /* * final IType newType = compilationUnit.findPrimaryType(); String * superClassName = newType.getSuperclassName(); if * (!isEmpty(superClassName)) { final IType superClassType = * prj.findType(getFQNameFromFieldTypeName(newType.getSuperclassName(), * newType.getCompilationUnit())); final FastCodeContext fastCodeContext * = new FastCodeContext(superClassType); final * CreateSimilarDescriptorClass createSimilarDescriptorClass = new * CreateSimilarDescriptorClass.Builder().withClassType( * CLASS_TYPE.CLASS).build(); for (final IMethod method : * superClassType.getMethods()) { if (method.isConstructor()) { * overrideConstructor(method, newType); final MethodBuilder * methodBuilder = new SimilarMethodBuilder(fastCodeContext); * methodBuilder.buildMethod(method, newType, null, * createSimilarDescriptorClass); } } } */ contextMap.put( "Class_" + compilationUnit.getElementName(), new FastCodeObject(compilationUnit, ACTION_ENTITY.Class.getValue())); if (!createFileAlone) { final IFile fileObj = (IFile) compilationUnit.findPrimaryType().getResource(); // .getLocationURI()); List<FastCodeEntityHolder> chngsForType = ((Map<Object, List<FastCodeEntityHolder>>) contextMap.get(FC_OBJ_CREATED)).get(fileObj); if (chngsForType == null) { chngsForType = new ArrayList<FastCodeEntityHolder>(); chngsForType.add( new FastCodeEntityHolder( PLACEHOLDER_CLASS, new FastCodeType(compilationUnit.findPrimaryType()))); } ((Map<Object, List<FastCodeEntityHolder>>) contextMap.get(FC_OBJ_CREATED)) .put(fileObj, chngsForType); } /*final Map<String, Object> listofChange = ((Map<Object, Map<String, Object>>) contextMap.get("changes_for_File")).get(file); if (chngsForType == null) { chngsForType = new HashMap<String, Object>(); chngsForType.put("class", CREATE_CLASS); //fastCodeCache.getCommentKey().get(fastCodeCache.getCommentKey().indexOf("create.class.field")) } ((Map<Object, Map<String, Object>>) contextMap.get("changes_for_File")).put(file, listofChange);*/ }
public void run(IMarker marker) { IFile file = (IFile) javaDeclaration.getResource(); try { ICompilationUnit original = EclipseUtil.getCompilationUnit(file); if (original == null) { return; } ICompilationUnit compilationUnit = original.getWorkingCopy(new NullProgressMonitor()); String lineDelim = JavaPropertyGenerator.getLineDelimiterUsed(compilationUnit); Hashtable<String, String> options = JavaCore.getOptions(); int tabSize = new Integer(options.get("org.eclipse.jdt.core.formatter.tabulation.size")); StringBuffer tabBuf = new StringBuffer(); for (int i = 0; i < tabSize; i++) tabBuf.append(" "); String tab = tabBuf.toString(); IType type = compilationUnit.findPrimaryType(); IField field = type.getField(property.getName()); String propertyType = ""; if (field != null && field.exists()) { propertyType = field.getTypeSignature(); } else { propertyType = "String"; // $NON-NLS-1$ StringBuffer buf = new StringBuffer(); buf.append( tab + "private " + propertyType + " " + property.getName() + ";"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ buf.append(lineDelim); field = type.createField(buf.toString(), null, false, new NullProgressMonitor()); if (field != null) { IBuffer buffer = compilationUnit.getBuffer(); buffer.replace( field.getSourceRange().getOffset(), field.getSourceRange().getLength(), buf.toString()); synchronized (compilationUnit) { compilationUnit.reconcile(ICompilationUnit.NO_AST, true, null, null); } } } IMethod oldMethod = GetterSetterUtil.getSetter(field); if (oldMethod == null || !oldMethod.exists()) { String setterName = GetterSetterUtil.getSetterName(field, null); // JavaPropertyGenerator.createSetter(compilationUnit, type, "public", // field.getTypeSignature(), setterName, lineDelim); String stub = GetterSetterUtil.getSetterStub(field, setterName, true, Flags.AccPublic); IMethod newMethod = type.createMethod(stub, null, false, new NullProgressMonitor()); if (newMethod != null) { IBuffer buffer = compilationUnit.getBuffer(); // format StringBuffer buf = new StringBuffer(); buf.append(lineDelim); buf.append( tab + "public void " + setterName + "(" + propertyType + " " + property.getName() + "){"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ buf.append(lineDelim); buf.append(tab + tab + "this." + property.getName() + " = " + property.getName() + ";"); buf.append(lineDelim); buf.append(tab + "}"); buf.append(lineDelim); buffer.replace( newMethod.getSourceRange().getOffset(), newMethod.getSourceRange().getLength(), buf.toString()); } } compilationUnit.commitWorkingCopy(false, new NullProgressMonitor()); compilationUnit.discardWorkingCopy(); } catch (CoreException ex) { SeamGuiPlugin.getPluginLog().logError(ex); } }
// two different source folders ignore only from one public void test002() throws CoreException { ICompilationUnit x = null; ICompilationUnit y = null; try { IJavaProject project = createJavaProject("P", new String[] {}, new String[] {"JCL_LIB"}, "bin"); project.setOption(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR); IClasspathEntry[] originalCP = project.getRawClasspath(); IClasspathEntry[] newCP = new IClasspathEntry[originalCP.length + 2]; System.arraycopy(originalCP, 0, newCP, 0, originalCP.length); newCP[originalCP.length] = JavaCore.newSourceEntry( new Path("/P/src"), null, null, null, new IClasspathAttribute[] {ATTR_IGNORE_OPTIONAL_PROBLEMS_TRUE}); newCP[originalCP.length + 1] = JavaCore.newSourceEntry(new Path("/P/src2")); project.setRawClasspath(newCP, null); createFolder("/P/src/p"); IFile fileX = createFile( "/P/src/p/X.java", "package p;\n" + "public class X {\n" + " public void foo() {\n" + " int i;\n" + " }\n" + "}"); x = (ICompilationUnit) JavaCore.create(fileX); createFolder("/P/src2/q"); IFile fileY = createFile( "/P/src2/q/Y.java", "package q;\n" + "public class Y {\n" + " public void foo() {\n" + " int i;\n" + " }\n" + "}"); y = (ICompilationUnit) JavaCore.create(fileY); ProblemRequestor problemRequestorX = new ProblemRequestor(); WorkingCopyOwner ownerX = newWorkingCopyOwner(problemRequestorX); x.getWorkingCopy(ownerX, null); assertProblems("Unexpected problems", "----------\n" + "----------\n", problemRequestorX); ProblemRequestor problemRequestorY = new ProblemRequestor(); WorkingCopyOwner ownerY = newWorkingCopyOwner(problemRequestorY); y.getWorkingCopy(ownerY, null); assertProblems( "Unexpected problems value", "----------\n" + "1. ERROR in /P/src2/q/Y.java\n" + "The value of the local variable i is not used\n" + "----------\n", problemRequestorY); } finally { if (x != null) { x.discardWorkingCopy(); } if (y != null) { y.discardWorkingCopy(); } deleteProject("P"); } }