/** * Removes contents of {@link #getPackageP()}, of {@link #getRoot()} (except for p) and of the * Java project (except for src and the JRE library). * * @throws Exception in case of errors */ protected void tearDown() throws Exception { refreshFromLocal(); performDummySearch(); final boolean pExists = getPackageP().exists(); if (pExists) { tryDeletingAllJavaChildren(getPackageP()); tryDeletingAllNonJavaChildResources(getPackageP()); } if (getRoot().exists()) { IJavaElement[] packages = getRoot().getChildren(); for (int i = 0; i < packages.length; i++) { IPackageFragment pack = (IPackageFragment) packages[i]; if (!pack.equals(getPackageP()) && pack.exists() && !pack.isReadOnly()) if (pack.isDefaultPackage()) pack.delete(true, null); else JavaProjectHelper.delete(pack.getResource()); // also delete packages with subpackages } // Restore package 'p' if (!pExists) getRoot().createPackageFragment("p", true, null); tryDeletingAllNonJavaChildResources(getRoot()); } restoreTestProject(); }
/* (non-Javadoc) * @see org.eclipse.jdt.internal.corext.refactoring.base.JDTChange#getModifiedResource() */ @Override protected IResource getModifiedResource() { IPackageFragment pack = getPackage(); if (pack != null) { return pack.getResource(); } return null; }
@Override protected boolean initialize(Object element) { if (element instanceof IType) { IType type = (IType) element; IJavaProject javaProject = (IJavaProject) type.getAncestor(IJavaElement.JAVA_PROJECT); mProject = javaProject.getProject(); IResource manifestResource = mProject.findMember(AdtConstants.WS_SEP + SdkConstants.FN_ANDROID_MANIFEST_XML); if (manifestResource == null || !manifestResource.exists() || !(manifestResource instanceof IFile)) { RefactoringUtil.logInfo( "Invalid or missing the " + SdkConstants.FN_ANDROID_MANIFEST_XML + " in the " + mProject.getName() + " project."); return false; } mManifestFile = (IFile) manifestResource; ManifestData manifestData; manifestData = AndroidManifestHelper.parseForData(mManifestFile); if (manifestData == null) { return false; } mAppPackage = manifestData.getPackage(); mOldFqcn = type.getFullyQualifiedName(); Object destination = getArguments().getDestination(); if (destination instanceof IPackageFragment) { IPackageFragment packageFragment = (IPackageFragment) destination; mNewFqcn = packageFragment.getElementName() + "." + type.getElementName(); } else if (destination instanceof IResource) { try { IPackageFragment[] fragments = javaProject.getPackageFragments(); for (IPackageFragment fragment : fragments) { IResource resource = fragment.getResource(); if (resource.equals(destination)) { mNewFqcn = fragment.getElementName() + '.' + type.getElementName(); break; } } } catch (JavaModelException e) { // pass } } return mOldFqcn != null && mNewFqcn != null; } return false; }
@Override public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException { final Map<IFile, TextChange> fileChanges = new HashMap<IFile, TextChange>(); IResourceProxyVisitor visitor = new IResourceProxyVisitor() { public boolean visit(IResourceProxy proxy) throws CoreException { if ((proxy.getType() == IResource.FOLDER) || (proxy.getType() == IResource.PROJECT)) { return true; } if (!((proxy.getType() == IResource.FILE) && proxy.getName().toLowerCase().endsWith(".bnd"))) { return false; } /* we're dealing with a *.bnd file */ /* get the proxied file */ IFile resource = (IFile) proxy.requestResource(); /* read the file as a single string */ String bndFileText = null; try { bndFileText = FileUtils.readFully(resource).get(); } catch (Exception e) { String str = "Could not read file " + proxy.getName(); logger.logError(str, e); throw new OperationCanceledException(str); } /* * get the previous change for this file if it exists, or otherwise create a new change for it, but do * not store it yet: wait until we know if there are actually changes in the file */ TextChange fileChange = getTextChange(resource); final boolean fileChangeIsNew = (fileChange == null); if (fileChange == null) { fileChange = new TextFileChange(proxy.getName(), resource); fileChange.setEdit(new MultiTextEdit()); } TextEdit rootEdit = fileChange.getEdit(); /* loop over all renames to perform */ for (Map.Entry<IPackageFragment, RenameArguments> entry : pkgFragments.entrySet()) { IPackageFragment pkgFragment = entry.getKey(); RenameArguments arguments = entry.getValue(); final String oldName = pkgFragment.getElementName(); final String newName = arguments.getNewName(); Pattern pattern = Pattern.compile( /* match start boundary */ "(^|" + grammarSeparator + ")" + /* match itself / package name */ "(" + Pattern.quote(oldName) + ")" + /* match end boundary */ "(" + grammarSeparator + "|" + Pattern.quote(".*") + "|" + Pattern.quote("\\") + "|$)"); /* find all matches to replace and add them to the root edit */ Matcher matcher = pattern.matcher(bndFileText); while (matcher.find()) { rootEdit.addChild( new ReplaceEdit(matcher.start(2), matcher.group(2).length(), newName)); } pattern = Pattern.compile( /* match start boundary */ "(^|" + grammarSeparator + ")" + /* match bundle activator */ "(Bundle-Activator\\s*:\\s*)" + /* match itself / package name */ "(" + Pattern.quote(oldName) + ")" + /* match class name */ "(\\.[^\\.]+)" + /* match end boundary */ "(" + grammarSeparator + "|" + Pattern.quote("\\") + "|$)"); /* find all matches to replace and add them to the root edit */ matcher = pattern.matcher(bndFileText); while (matcher.find()) { rootEdit.addChild( new ReplaceEdit(matcher.start(3), matcher.group(3).length(), newName)); } } /* * only store the changes when no changes were stored before for this file and when there are actually * changes. */ if (fileChangeIsNew && rootEdit.hasChildren()) { fileChanges.put(resource, fileChange); } return false; } }; /* determine which projects have to be visited */ Set<IProject> projectsToVisit = new HashSet<IProject>(); for (IPackageFragment pkgFragment : pkgFragments.keySet()) { projectsToVisit.add(pkgFragment.getResource().getProject()); for (IProject projectToVisit : pkgFragment.getResource().getProject().getReferencingProjects()) { projectsToVisit.add(projectToVisit); } for (IProject projectToVisit : pkgFragment.getResource().getProject().getReferencedProjects()) { projectsToVisit.add(projectToVisit); } } /* visit the projects */ for (IProject projectToVisit : projectsToVisit) { projectToVisit.accept(visitor, IContainer.NONE); } if (fileChanges.isEmpty()) { /* no changes at all */ return null; } /* build a composite change with all changes */ CompositeChange cs = new CompositeChange(changeTitle); for (TextChange fileChange : fileChanges.values()) { cs.add(fileChange); } return cs; }
/** * @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);*/ }
@Override public void run(IAction action) { if (action.getId() == FILE_LOCATION_ACTION) { // 文件 } else if (action.getId() == FOLDER_LOCATION_ACTION) { // 文件夹 } else { // 其他 } if (selection instanceof IStructuredSelection) { IStructuredSelection sel = (IStructuredSelection) selection; Object obj = sel.getFirstElement(); /* * Donot work on IWorkSpace if(obj instanceof IResource) { IResource resource = (IResource) Platform.getAdapterManager().getAdapter(obj,IResource.class); if (resource != null) { try { IPath path = resource.getRawLocation() ; File winfile = path.toFile(); String winPath = winfile.getParent(); Runtime.getRuntime().exec("explorer " + winPath); } catch (IOException e) { e.printStackTrace(); } } } */ IPath path = null; System.out.println(obj.getClass()); if (obj instanceof IFile) { IFile file = (IFile) Platform.getAdapterManager().getAdapter(obj, IFile.class); path = file.getRawLocation(); } else if (obj instanceof IFolder) { IFolder folder = (IFolder) Platform.getAdapterManager().getAdapter(obj, IFolder.class); path = folder.getRawLocation(); } else if (obj instanceof IPackageFragmentRoot) { if (obj.getClass() .toString() .equals("class org.eclipse.jdt.internal.core.JarPackageFragmentRoot")) { MessageDialog.openInformation( workbenchpart.getSite().getShell(), "NeoFactory Enhance Plugins", "Sorry, this operation is not supported. \n\n" + "JarPackageFragmentRoot extends from PackageFragmentRoot, \n" + "PackageFragmentRoot implements IPackageFragmentRoot, \n" + "so I cannot hide this menu as while as I need that shows on source packages."); } else { IPackageFragmentRoot packageFragRoot = (IPackageFragmentRoot) Platform.getAdapterManager().getAdapter(obj, IPackageFragmentRoot.class); path = packageFragRoot.getResource().getRawLocation(); } } else if (obj instanceof IPackageFragment) { IPackageFragment packageFrag = (IPackageFragment) Platform.getAdapterManager().getAdapter(obj, IPackageFragment.class); path = packageFrag.getResource().getRawLocation(); } else if (obj instanceof ICompilationUnit) { ICompilationUnit unit = (ICompilationUnit) Platform.getAdapterManager().getAdapter(obj, ICompilationUnit.class); path = unit.getResource().getRawLocation(); } if (path != null) { try { File winfile = path.toFile(); String winPath = winfile.getParent(); Runtime.getRuntime().exec("explorer " + winPath); } catch (IOException e) { e.printStackTrace(); } } } }