diff --git a/org.ntlab.refactoring.decouplingClasses/src/org/ntlab/refactoring/decouplingClasses/DecoupleClassesRefactoringHandler.java b/org.ntlab.refactoring.decouplingClasses/src/org/ntlab/refactoring/decouplingClasses/DecoupleClassesRefactoringHandler.java index 8552941..be75e2e 100644 --- a/org.ntlab.refactoring.decouplingClasses/src/org/ntlab/refactoring/decouplingClasses/DecoupleClassesRefactoringHandler.java +++ b/org.ntlab.refactoring.decouplingClasses/src/org/ntlab/refactoring/decouplingClasses/DecoupleClassesRefactoringHandler.java @@ -113,8 +113,8 @@ null /* use primary owner */, null /* no progress monitor */); } -// ITextSelection selection = (ITextSelection) HandlerUtil.getCurrentSelection(event); - ITextSelection selection = (ITextSelection) HandlerUtil.getActiveMenuSelection(event); + ITextSelection selection = (ITextSelection) HandlerUtil.getCurrentSelection(event); +// ITextSelection selection = (ITextSelection) HandlerUtil.getActiveMenuSelection(event); IJavaElement[] elements = ((ICodeAssist)typeRoot).codeSelect(selection.getOffset() + selection.getLength(), 0); if (elements.length > 0) { return elements[0]; diff --git a/org.ntlab.refactoring.decouplingClasses/src/org/ntlab/refactoring/decouplingClasses/DecoupleClassesRefactoringProcessor.java b/org.ntlab.refactoring.decouplingClasses/src/org/ntlab/refactoring/decouplingClasses/DecoupleClassesRefactoringProcessor.java index 59da7c7..afa2492 100644 --- a/org.ntlab.refactoring.decouplingClasses/src/org/ntlab/refactoring/decouplingClasses/DecoupleClassesRefactoringProcessor.java +++ b/org.ntlab.refactoring.decouplingClasses/src/org/ntlab/refactoring/decouplingClasses/DecoupleClassesRefactoringProcessor.java @@ -1,17 +1,82 @@ package org.ntlab.refactoring.decouplingClasses; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.text.MessageFormat; +import java.util.ArrayList; import java.util.List; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.ProjectScope; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; +import org.eclipse.core.runtime.Platform; +import org.eclipse.core.runtime.SubProgressMonitor; +import org.eclipse.core.runtime.content.IContentType; +import org.eclipse.core.runtime.preferences.IScopeContext; +import org.eclipse.core.runtime.preferences.InstanceScope; +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IJavaModelStatusConstants; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.core.ToolFactory; +import org.eclipse.jdt.core.compiler.IScanner; +import org.eclipse.jdt.core.compiler.ITerminalSymbols; +import org.eclipse.jdt.core.compiler.InvalidInputException; +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.ASTParser; +import org.eclipse.jdt.core.dom.ASTVisitor; +import org.eclipse.jdt.core.dom.BodyDeclaration; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.ExpressionStatement; +import org.eclipse.jdt.core.dom.FieldDeclaration; +import org.eclipse.jdt.core.dom.ITypeBinding; +import org.eclipse.jdt.core.dom.IVariableBinding; +import org.eclipse.jdt.core.dom.ImportDeclaration; +import org.eclipse.jdt.core.dom.InfixExpression; +import org.eclipse.jdt.core.dom.MethodDeclaration; +import org.eclipse.jdt.core.dom.MethodInvocation; +import org.eclipse.jdt.core.dom.Modifier; +import org.eclipse.jdt.core.dom.Modifier.ModifierKeyword; +import org.eclipse.jdt.core.dom.PackageDeclaration; +import org.eclipse.jdt.core.dom.PrimitiveType; +import org.eclipse.jdt.core.dom.QualifiedName; +import org.eclipse.jdt.core.dom.SingleVariableDeclaration; +import org.eclipse.jdt.core.dom.StringLiteral; +import org.eclipse.jdt.core.dom.Type; +import org.eclipse.jdt.core.dom.TypeDeclaration; +import org.eclipse.jdt.core.dom.VariableDeclarationFragment; +import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; +import org.eclipse.jdt.core.dom.rewrite.ListRewrite; +import org.eclipse.jdt.ui.CodeGeneration; +import org.eclipse.jdt.ui.PreferenceConstants; +import org.eclipse.jface.text.Document; import org.eclipse.ltk.core.refactoring.Change; +import org.eclipse.ltk.core.refactoring.CompositeChange; import org.eclipse.ltk.core.refactoring.NullChange; import org.eclipse.ltk.core.refactoring.RefactoringStatus; import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext; import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant; import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor; import org.eclipse.ltk.core.refactoring.participants.SharableParticipants; +import org.eclipse.ltk.core.refactoring.resource.DeleteResourceChange; +import org.eclipse.ltk.core.refactoring.resource.ResourceChange; +import org.eclipse.osgi.util.TextProcessor; +import org.eclipse.text.edits.TextEdit; +import org.eclipse.ui.ide.ResourceUtil; import org.ntlab.refactoring.decouplingClasses.descriptors.DecoupleClassesDescriptor; import test.pseudocode.core.DepthFirstTopologicalSorter; @@ -77,8 +142,9 @@ public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException { System.out.println(this.getClass().getSimpleName() + "#createChange()"); - // Change change = createRenameChange(); - Change change = new NullChange();// createNewClassChanges(); +// Change change = createRenameChange(); +// Change change = new NullChange();// createNewClassChanges(); + Change change = createNewClassChanges(); return change; } @@ -112,316 +178,360 @@ return descriptor; } -// private Change createNewClassChanges() throws CoreException { -// CompositeChange change = new CompositeChange(DecoupleClassesRefactoring.NAME); -// -// // TODO: �w��̃p�b�P�[�W�̗L���̊m�F�ƁA�Ȃ���ΐ�������Change�̒lj��B -// -// IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) descriptor.getTargetType().getCompilationUnit().getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); -// IPackageFragment packageFragment = packageFragmentRoot.getPackageFragment(descriptor.getPackage()); -// -// ICompilationUnit cu = packageFragment.getCompilationUnit(descriptor.getNewClassName() + ".java"); -// ICompilationUnit workingCopy = cu.getWorkingCopy(null); -// workingCopy.getBuffer().setContents("class " + descriptor.getNewClassName() + " {}"); -// -// ASTParser parser = ASTParser.newParser(AST.JLS8); -// parser.setKind(ASTParser.K_COMPILATION_UNIT); -// parser.setResolveBindings(true); -// parser.setSource(workingCopy); -// -// CompilationUnit unit = (CompilationUnit) parser.createAST(null); -// unit.recordModifications(); -// -// ASTRewrite rewrite = ASTRewrite.create(unit.getAST()); -// -// TypeDeclaration typeDeclaration = createClassDeclaration(unit.getAST()); -// -// ListRewrite typesRewrite = rewrite.getListRewrite(unit, CompilationUnit.TYPES_PROPERTY); -// typesRewrite.replace((ASTNode) typesRewrite.getOriginalList().get(0), typeDeclaration, null); -// -// Document document = new Document(workingCopy.getSource()); -// TextEdit edit = rewrite.rewriteAST(document, null); -// try { -// edit.apply(document); -// } catch (MalformedTreeException | BadLocationException e) { -// e.printStackTrace(); -// } -// -// String newSource = document.get(); -// workingCopy.getBuffer().setContents(newSource); -// -// change.add(new CreateNewClassChange(cu, document.get())); -// -// workingCopy.discardWorkingCopy(); -// -// return change; -// } + private Change createNewClassChanges() throws CoreException { + CompositeChange change = new CompositeChange(DecoupleClassesRefactoring.NAME); - // private static String getProjectLineDelimiter(IJavaProject javaProject) { - // IProject project= null; - // if (javaProject != null) - // project= javaProject.getProject(); - // - // String lineDelimiter= getLineDelimiterPreference(project); - // if (lineDelimiter != null) - // return lineDelimiter; - // - // return System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ - // } + // TODO: �w��̃p�b�P�[�W�̗L���̊m�F�ƁA�Ȃ���ΐ�������Change�̒lj��B - // public static String getLineDelimiterPreference(IProject project) { - // IScopeContext[] scopeContext; - // if (project != null) { - // // project preference - // scopeContext= new IScopeContext[] { new ProjectScope(project) }; - // String lineDelimiter= Platform.getPreferencesService().getString(Platform.PI_RUNTIME, Platform.PREF_LINE_SEPARATOR, null, scopeContext); - // if (lineDelimiter != null) - // return lineDelimiter; - // } - // // workspace preference - // scopeContext= new IScopeContext[] { InstanceScope.INSTANCE }; - // String platformDefault= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ - // return Platform.getPreferencesService().getString(Platform.PI_RUNTIME, Platform.PREF_LINE_SEPARATOR, platformDefault, scopeContext); - // } + IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) descriptor.getTargetType().getCompilationUnit().getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); + IPackageFragment packageFragment = packageFragmentRoot.getPackageFragment(descriptor.getPackage()); - // private String getTypeComment(ICompilationUnit parentCU, String lineDelimiter) throws CoreException { - // if (Boolean.valueOf(PreferenceConstants.getPreference(PreferenceConstants.CODEGEN_ADD_COMMENTS, parentCU.getJavaProject())).booleanValue()) { - // StringBuffer typeName = new StringBuffer(); - // typeName.append(descriptor.getNewClassName()); - // String[] typeParamNames= new String[0]; - // String comment= CodeGeneration.getTypeComment(parentCU, typeName.toString(), typeParamNames, lineDelimiter); - // if (comment != null && isValidComment(comment)) { - // return comment; - // } - // } - // return null; - // } + ICompilationUnit cu = packageFragment.getCompilationUnit(descriptor.getNewClassName() + ".java"); + ICompilationUnit workingCopy = cu.getWorkingCopy(null); + workingCopy.getBuffer().setContents("class " + descriptor.getNewClassName() + " {}"); - // private boolean isValidComment(String template) { - // IScanner scanner = ToolFactory.createScanner(true, false, false, false); - // scanner.setSource(template.toCharArray()); - // try { - // int next = scanner.getNextToken(); - // while (next == ITerminalSymbols.TokenNameCOMMENT_BLOCK || next == ITerminalSymbols.TokenNameCOMMENT_JAVADOC || next == ITerminalSymbols.TokenNameCOMMENT_LINE) { - // next= scanner.getNextToken(); - // } - // return next == ITerminalSymbols.TokenNameEOF; - // } catch (InvalidInputException e) { - // } - // return false; - // } + ASTParser parser = ASTParser.newParser(AST.JLS8); + parser.setKind(ASTParser.K_COMPILATION_UNIT); + parser.setResolveBindings(true); + parser.setSource(workingCopy); -// @SuppressWarnings("unchecked") -// private TypeDeclaration createClassDeclaration(AST ast) { -// TypeDeclaration typeDeclaration = ast.newTypeDeclaration(); -// -// typeDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD)); -// typeDeclaration.setName(ast.newSimpleName(descriptor.getNewClassName())); -// List body = typeDeclaration.bodyDeclarations(); -// -// FieldDeclaration fieldDeclaration = createField(ast); -// body.add(fieldDeclaration); -// -// return typeDeclaration; -// } + CompilationUnit unit = (CompilationUnit) parser.createAST(null); + unit.recordModifications(); -// @SuppressWarnings("unchecked") -// private FieldDeclaration createField(AST ast) { -// VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment(); -// String fieldName = Character.toLowerCase(descriptor.getTargetName().charAt(0)) + descriptor.getTargetName().substring(1); -// fragment.setName(ast.newSimpleName(fieldName)); -// FieldDeclaration fieldDeclaration = ast.newFieldDeclaration(fragment); -// fieldDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PRIVATE_KEYWORD)); -// -// ASTParser parser = ASTParser.newParser(AST.JLS8); -// IType targetType = descriptor.getTargetType(); -// ICompilationUnit compilationUnit = targetType.getCompilationUnit(); -// parser.setSource(compilationUnit); -// parser.setResolveBindings(true); -// CompilationUnit unit = (CompilationUnit) parser.createAST(null); -// final List results = new ArrayList<>(); -// unit.accept(new ASTVisitor() { -// }); -// fieldDeclaration.setType(results.get(0)); -// -// return fieldDeclaration; -// } + ASTRewrite rewrite = ASTRewrite.create(unit.getAST()); -// @SuppressWarnings("unchecked") -// private TypeDeclaration test(CompilationUnit unit) { -// AST ast = unit.getAST(); -// -// PackageDeclaration packageDeclaration = ast.newPackageDeclaration(); -// packageDeclaration.setName(ast.newSimpleName("example")); -// unit.setPackage(packageDeclaration); -// -// ImportDeclaration importDeclaration = ast.newImportDeclaration(); -// QualifiedName name = ast.newQualifiedName(ast.newSimpleName("java"), ast.newSimpleName("util")); -// importDeclaration.setName(name); -// importDeclaration.setOnDemand(true); -// unit.imports().add(importDeclaration); -// -// TypeDeclaration type = ast.newTypeDeclaration(); -// type.setInterface(false); -// type.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD)); -// type.setName(ast.newSimpleName("HelloWorld")); -// -// MethodDeclaration methodDeclaration = ast.newMethodDeclaration(); -// methodDeclaration.setConstructor(false); -// List modifiers = methodDeclaration.modifiers(); -// modifiers.add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD)); -// modifiers.add(ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD)); -// methodDeclaration.setName(ast.newSimpleName("main")); -// methodDeclaration.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID)); -// SingleVariableDeclaration variableDeclaration = ast.newSingleVariableDeclaration(); -// variableDeclaration.setType(ast.newArrayType(ast.newSimpleType(ast.newSimpleName("String")))); -// variableDeclaration.setName(ast.newSimpleName("args")); -// methodDeclaration.parameters().add(variableDeclaration); -// -// org.eclipse.jdt.core.dom.Block block = ast.newBlock(); -// MethodInvocation methodInvocation = ast.newMethodInvocation(); -// name = ast.newQualifiedName(ast.newSimpleName("System"), ast.newSimpleName("out")); -// methodInvocation.setExpression(name); -// methodInvocation.setName(ast.newSimpleName("println")); -// InfixExpression infixExpression = ast.newInfixExpression(); -// infixExpression.setOperator(InfixExpression.Operator.PLUS); -// StringLiteral literal = ast.newStringLiteral(); -// literal.setLiteralValue("Hello"); -// infixExpression.setLeftOperand(literal); -// literal = ast.newStringLiteral(); -// literal.setLiteralValue(" world"); -// infixExpression.setRightOperand(literal); -// methodInvocation.arguments().add(infixExpression); -// ExpressionStatement expressionStatement = ast.newExpressionStatement(methodInvocation); -// block.statements().add(expressionStatement); -// methodDeclaration.setBody(block); -// type.bodyDeclarations().add(methodDeclaration); -// -// unit.types().add(type); -// -// return type; -// } + TypeDeclaration typeDeclaration = createClassDeclaration(unit.getAST()); -// private class CreateNewClassChange extends ResourceChange { -// private IPath path; -// private String fSource; -// private String encoding; -// private boolean explicitEncoding; -// -// public CreateNewClassChange(ICompilationUnit newClassCu, String source) throws CoreException { -// path = newClassCu.getResource().getFullPath(); -// this.fSource = source; -// encoding = ResourceUtil.getFile(newClassCu).getCharset(false); -// explicitEncoding = encoding != null; -// } -// -// @Override -// public String getName() { -// return MessageFormat.format("Create class", new Object[] {getPathLabel(path, false)}); -// } -// -// public String getPathLabel(IPath path, boolean isOSPath) { -// String label; -// if (isOSPath) { -// label= path.toOSString(); -// } else { -// label= path.makeRelative().toString(); -// } -// return markLTR(label); -// } -// -// public String markLTR(String string) { -// String testString= "args : String[]"; //$NON-NLS-1$ -// -// if (!(testString != TextProcessor.process(testString))) { -// return string; -// } -// -// return TextProcessor.process(string); -// } -// -// @Override -// protected IResource getModifiedResource() { -// return ResourcesPlugin.getWorkspace().getRoot().getFile(path); -// } -// -// @Override -// public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException { -// return null; -// } -// -// @Override -// public Change perform(IProgressMonitor pm) throws CoreException, OperationCanceledException { -// InputStream inputStream = null; -// try { -// pm.beginTask("Creating java file...", 3); -// -// initializeEncoding(); -// IFile file = getOldFile(new SubProgressMonitor(pm, 1)); -// try { -// inputStream= new ByteArrayInputStream(fSource.getBytes(encoding)); -// file.create(inputStream, false, new SubProgressMonitor(pm, 1)); -// if (explicitEncoding) { -// file.setCharset(encoding, new SubProgressMonitor(pm, 1)); -// } else { -// pm.worked(1); -// } -// return new DeleteResourceChange(file.getFullPath(), true); -// } catch (UnsupportedEncodingException e) { -// throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); -// } -// } finally { -// try { -// if (inputStream != null) -// inputStream.close(); -// } catch (IOException ioe) { -// throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION); -// } finally { -// pm.done(); -// } -// } -// } -// -// protected IFile getOldFile(IProgressMonitor pm) throws OperationCanceledException { -// pm.beginTask("", 1); //$NON-NLS-1$ -// try { -// return ResourcesPlugin.getWorkspace().getRoot().getFile(path); -// } finally { -// pm.done(); -// } -// } -// -// private void initializeEncoding() { -// if (encoding == null) { -// explicitEncoding= false; -// IFile file= ResourcesPlugin.getWorkspace().getRoot().getFile(path); -// if (file != null) { -// try { -// if (file.exists()) { -// encoding= file.getCharset(false); -// if (encoding == null) { -// encoding= file.getCharset(true); -// } else { -// explicitEncoding = true; -// } -// } else { -// IContentType contentType= Platform.getContentTypeManager().findContentTypeFor(file.getName()); -// if (contentType != null) -// encoding = contentType.getDefaultCharset(); -// if (encoding == null) -// encoding = file.getCharset(true); -// } -// } catch (CoreException e) { -// encoding= ResourcesPlugin.getEncoding(); -// explicitEncoding= true; -// } -// } else { -// encoding= ResourcesPlugin.getEncoding(); -// explicitEncoding= true; -// } -// } -// Assert.isNotNull(encoding); -// } -// } + ListRewrite typesRewrite = rewrite.getListRewrite(unit, CompilationUnit.TYPES_PROPERTY); + typesRewrite.replace((ASTNode) typesRewrite.getOriginalList().get(0), typeDeclaration, null); + + Document document = new Document(workingCopy.getSource()); + TextEdit edit = rewrite.rewriteAST(document, null); + try { + edit.apply(document); + } catch(Exception e) { + e.printStackTrace(); + } + + String newSource = document.get(); + workingCopy.getBuffer().setContents(newSource); + + change.add(new CreateNewClassChange(cu, document.get())); + + workingCopy.discardWorkingCopy(); + + return change; + } + + private static String getProjectLineDelimiter(IJavaProject javaProject) { + IProject project= null; + if (javaProject != null) + project= javaProject.getProject(); + + String lineDelimiter= getLineDelimiterPreference(project); + if (lineDelimiter != null) + return lineDelimiter; + + return System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + public static String getLineDelimiterPreference(IProject project) { + IScopeContext[] scopeContext; + if (project != null) { + // project preference + scopeContext= new IScopeContext[] { new ProjectScope(project) }; + String lineDelimiter= Platform.getPreferencesService().getString(Platform.PI_RUNTIME, Platform.PREF_LINE_SEPARATOR, null, scopeContext); + if (lineDelimiter != null) + return lineDelimiter; + } + // workspace preference + scopeContext= new IScopeContext[] { InstanceScope.INSTANCE }; + String platformDefault= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ + return Platform.getPreferencesService().getString(Platform.PI_RUNTIME, Platform.PREF_LINE_SEPARATOR, platformDefault, scopeContext); + } + + private String getTypeComment(ICompilationUnit parentCU, String lineDelimiter) throws CoreException { + if (Boolean.valueOf(PreferenceConstants.getPreference(PreferenceConstants.CODEGEN_ADD_COMMENTS, parentCU.getJavaProject())).booleanValue()) { + StringBuffer typeName = new StringBuffer(); + typeName.append(descriptor.getNewClassName()); + String[] typeParamNames= new String[0]; + String comment= CodeGeneration.getTypeComment(parentCU, typeName.toString(), typeParamNames, lineDelimiter); + if (comment != null && isValidComment(comment)) { + return comment; + } + } + return null; + } + + private boolean isValidComment(String template) { + IScanner scanner = ToolFactory.createScanner(true, false, false, false); + scanner.setSource(template.toCharArray()); + try { + int next = scanner.getNextToken(); + while (next == ITerminalSymbols.TokenNameCOMMENT_BLOCK || next == ITerminalSymbols.TokenNameCOMMENT_JAVADOC || next == ITerminalSymbols.TokenNameCOMMENT_LINE) { + next= scanner.getNextToken(); + } + return next == ITerminalSymbols.TokenNameEOF; + } catch (InvalidInputException e) { + } + return false; + } + + @SuppressWarnings("unchecked") + private TypeDeclaration createClassDeclaration(AST ast) { + TypeDeclaration typeDeclaration = ast.newTypeDeclaration(); + + typeDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD)); + typeDeclaration.setName(ast.newSimpleName(descriptor.getNewClassName())); + List body = typeDeclaration.bodyDeclarations(); + + FieldDeclaration fieldDeclaration = createField(ast); + body.add(fieldDeclaration); + + return typeDeclaration; + } + + @SuppressWarnings("unchecked") + private FieldDeclaration createField(AST ast) { + VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment(); + String fieldName = Character.toLowerCase(descriptor.getTargetName().charAt(0)) + descriptor.getTargetName().substring(1); + fragment.setName(ast.newSimpleName(fieldName)); + FieldDeclaration fieldDeclaration = ast.newFieldDeclaration(fragment); + fieldDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PRIVATE_KEYWORD)); + + ASTParser parser = ASTParser.newParser(AST.JLS8); + IType targetType = descriptor.getTargetType(); + ICompilationUnit compilationUnit = targetType.getCompilationUnit(); + parser.setSource(compilationUnit); + parser.setResolveBindings(true); + CompilationUnit unit = (CompilationUnit) parser.createAST(null); + final List results = new ArrayList<>(); + unit.accept(new ASTVisitor() { + /** + * �N���X�錾�����‚���ƌĂ΂�郁�\�b�h + */ + public boolean visit(TypeDeclaration node) { + System.out.println("�N���X�錾"); + ITypeBinding typeBinding = node.resolveBinding();// �ڍׂȏ���ITypeBinding�C���X�^���X���g���Ď擾������ + ITypeBinding superClass = typeBinding.getSuperclass();// �e�N���X�̎擾 + ITypeBinding[] interfaces = typeBinding.getInterfaces();// �C���^�[�t�F�[�X�̎擾 + String className = typeBinding.getBinaryName();// �N���X���̎擾 + int modifiers = typeBinding.getModifiers();// "public static"�Ƃ��̎��ʎq + System.out.println("ClassName: " + className); + System.out.println("Modifiers: " + modifiers); + System.out.println("SuperClass: " + superClass.getBinaryName()); +// System.out.println("Interfaces: " + interfaces); + return super.visit(node); + } + /** + * �t�B�[���h�錾�����‚���ƌĂ΂�郁�\�b�h + */ + public boolean visit(FieldDeclaration node) { + System.out.println("�t�B�[���h�錾"); + System.out.println("Modifiers: " + node.getModifiers()); + System.out.println("Type: " + node.getType().toString()); + List fragments = node.fragments(); + for (Object frg : fragments) { + if (frg instanceof VariableDeclarationFragment) { + IVariableBinding variableBinding = ((VariableDeclarationFragment) frg) + .resolveBinding(); + System.out.println("Name: " + variableBinding.getName()); + } + } + return super.visit(node); + } + /** + * ���\�b�h�錾�����‚���ƌĂ΂�郁�\�b�h + */ + public boolean visit(MethodDeclaration node) { + System.out.println("���\�b�h�錾"); + System.out.println("MethodName: " + node.getName().getFullyQualifiedName()); + System.out.println("Modifiers: " + node.getModifiers()); + System.out.println("ReturnType: " + node.getReturnType2() + ""); + System.out.println("Parameters: "+ node.parameters().toString()); + return super.visit(node); + } + }); + fieldDeclaration.setType(results.get(0)); + + return fieldDeclaration; + } + + @SuppressWarnings("unchecked") + private TypeDeclaration test(CompilationUnit unit) { + AST ast = unit.getAST(); + + PackageDeclaration packageDeclaration = ast.newPackageDeclaration(); + packageDeclaration.setName(ast.newSimpleName("example")); + unit.setPackage(packageDeclaration); + + ImportDeclaration importDeclaration = ast.newImportDeclaration(); + QualifiedName name = ast.newQualifiedName(ast.newSimpleName("java"), ast.newSimpleName("util")); + importDeclaration.setName(name); + importDeclaration.setOnDemand(true); + unit.imports().add(importDeclaration); + + TypeDeclaration type = ast.newTypeDeclaration(); + type.setInterface(false); + type.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD)); + type.setName(ast.newSimpleName("HelloWorld")); + + MethodDeclaration methodDeclaration = ast.newMethodDeclaration(); + methodDeclaration.setConstructor(false); + List modifiers = methodDeclaration.modifiers(); + modifiers.add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD)); + modifiers.add(ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD)); + methodDeclaration.setName(ast.newSimpleName("main")); + methodDeclaration.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID)); + SingleVariableDeclaration variableDeclaration = ast.newSingleVariableDeclaration(); + variableDeclaration.setType(ast.newArrayType(ast.newSimpleType(ast.newSimpleName("String")))); + variableDeclaration.setName(ast.newSimpleName("args")); + methodDeclaration.parameters().add(variableDeclaration); + + org.eclipse.jdt.core.dom.Block block = ast.newBlock(); + MethodInvocation methodInvocation = ast.newMethodInvocation(); + name = ast.newQualifiedName(ast.newSimpleName("System"), ast.newSimpleName("out")); + methodInvocation.setExpression(name); + methodInvocation.setName(ast.newSimpleName("println")); + InfixExpression infixExpression = ast.newInfixExpression(); + infixExpression.setOperator(InfixExpression.Operator.PLUS); + StringLiteral literal = ast.newStringLiteral(); + literal.setLiteralValue("Hello"); + infixExpression.setLeftOperand(literal); + literal = ast.newStringLiteral(); + literal.setLiteralValue(" world"); + infixExpression.setRightOperand(literal); + methodInvocation.arguments().add(infixExpression); + ExpressionStatement expressionStatement = ast.newExpressionStatement(methodInvocation); + block.statements().add(expressionStatement); + methodDeclaration.setBody(block); + type.bodyDeclarations().add(methodDeclaration); + + unit.types().add(type); + + return type; + } + + private class CreateNewClassChange extends ResourceChange { + private IPath path; + private String fSource; + private String encoding; + private boolean explicitEncoding; + + public CreateNewClassChange(ICompilationUnit newClassCu, String source) throws CoreException { + path = newClassCu.getResource().getFullPath(); + this.fSource = source; + encoding = ResourceUtil.getFile(newClassCu).getCharset(false); + explicitEncoding = encoding != null; + } + + @Override + public String getName() { + return MessageFormat.format("Create class", new Object[] {getPathLabel(path, false)}); + } + + public String getPathLabel(IPath path, boolean isOSPath) { + String label; + if (isOSPath) { + label= path.toOSString(); + } else { + label= path.makeRelative().toString(); + } + return markLTR(label); + } + + public String markLTR(String string) { + String testString= "args : String[]"; //$NON-NLS-1$ + + if (!(testString != TextProcessor.process(testString))) { + return string; + } + + return TextProcessor.process(string); + } + + @Override + protected IResource getModifiedResource() { + return ResourcesPlugin.getWorkspace().getRoot().getFile(path); + } + + @Override + public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException { + return null; + } + + @Override + public Change perform(IProgressMonitor pm) throws CoreException, OperationCanceledException { + InputStream inputStream = null; + try { + pm.beginTask("Creating java file...", 3); + + initializeEncoding(); + IFile file = getOldFile(new SubProgressMonitor(pm, 1)); + try { + inputStream= new ByteArrayInputStream(fSource.getBytes(encoding)); + file.create(inputStream, false, new SubProgressMonitor(pm, 1)); + if (explicitEncoding) { + file.setCharset(encoding, new SubProgressMonitor(pm, 1)); + } else { + pm.worked(1); + } + return new DeleteResourceChange(file.getFullPath(), true); + } catch (UnsupportedEncodingException e) { + throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); + } + } finally { + try { + if (inputStream != null) + inputStream.close(); + } catch (IOException ioe) { + throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION); + } finally { + pm.done(); + } + } + } + + protected IFile getOldFile(IProgressMonitor pm) throws OperationCanceledException { + pm.beginTask("", 1); //$NON-NLS-1$ + try { + return ResourcesPlugin.getWorkspace().getRoot().getFile(path); + } finally { + pm.done(); + } + } + + private void initializeEncoding() { + if (encoding == null) { + explicitEncoding= false; + IFile file= ResourcesPlugin.getWorkspace().getRoot().getFile(path); + if (file != null) { + try { + if (file.exists()) { + encoding= file.getCharset(false); + if (encoding == null) { + encoding= file.getCharset(true); + } else { + explicitEncoding = true; + } + } else { + IContentType contentType= Platform.getContentTypeManager().findContentTypeFor(file.getName()); + if (contentType != null) + encoding = contentType.getDefaultCharset(); + if (encoding == null) + encoding = file.getCharset(true); + } + } catch (CoreException e) { + encoding= ResourcesPlugin.getEncoding(); + explicitEncoding= true; + } + } else { + encoding= ResourcesPlugin.getEncoding(); + explicitEncoding= true; + } + } + Assert.isNotNull(encoding); + } + } }