List of usage examples for org.eclipse.jdt.core.dom ImportDeclaration setOnDemand
public void setOnDemand(boolean onDemand)
From source file:com.idega.eclipse.ejbwizards.BeanCreator.java
License:Open Source License
protected void writeImports(AST ast, CompilationUnit unit, Set imports) { Iterator iter = imports.iterator(); while (iter.hasNext()) { String importName = (String) iter.next(); if (importName != null) { ImportDeclaration importDeclaration = ast.newImportDeclaration(); importDeclaration.setName(ast.newName(importName)); importDeclaration.setOnDemand(false); unit.imports().add(importDeclaration); }/*from w w w . j a v a 2 s . c om*/ } }
From source file:com.motorola.studio.android.generatecode.JavaCodeModifier.java
License:Apache License
@SuppressWarnings("unchecked") private void createImport(String name, CompilationUnit compUnit, boolean onDemand) { AST ast = compUnit.getAST();/*from ww w. j a va 2s . co m*/ ImportDeclaration importDeclaration = ast.newImportDeclaration(); importDeclaration.setName(ast.newName(name)); importDeclaration.setOnDemand(onDemand); compUnit.imports().add(importDeclaration); }
From source file:de.ovgu.cide.export.physical.ahead.ExportJavaFileJob.java
License:Open Source License
private void addCideJakUtilImport(CompilationUnit cunit) { AST ast = cunit.getAST();//w w w. j a v a 2 s . c o m ImportDeclaration imp = ast.newImportDeclaration(); SimpleName de = ast.newSimpleName("de"); QualifiedName deOvgu = ast.newQualifiedName(de, ast.newSimpleName("ovgu")); QualifiedName deOvguCide = ast.newQualifiedName(deOvgu, ast.newSimpleName("cide")); QualifiedName deOvguCideJakutil = ast.newQualifiedName(deOvguCide, ast.newSimpleName("jakutil")); imp.setName(deOvguCideJakutil); imp.setOnDemand(true); cunit.imports().add(imp); }
From source file:org.eclipse.emf.texo.generator.ImportResolver.java
License:Open Source License
/** * Determine all needed imports, retain existing imports if needed, update import section in the source and replace * all qualified names with their non-qualified equivalent (if there is an import statement). * /*from ww w.ja v a2 s . com*/ * @return the updated source */ public String resolve() { Check.isNotNullArgument(source, "source"); //$NON-NLS-1$ Check.isNotNullArgument(javaProject, "javaProject"); //$NON-NLS-1$ // get the package name and the list of existing and needed types final ImportReferenceCollector importReferenceCollector = new ImportReferenceCollector(); compilationUnit.accept(importReferenceCollector); // get the list of needed imports because of already present // non-qualified names. final List<ImportDeclaration> importDeclarations = determineCurrentNeededImports( importReferenceCollector.getExistingImports(), importReferenceCollector.getQualifiedTypes()); final List<String> cleanedQualifedNames = cleanQualifiedNames(importReferenceCollector.getQualifiedTypes()); // now determine which new ones should be added and if so prevent // collisions final List<String> importedNonQualifiedNames = importedNonQualifiedNames(importDeclarations); final List<String> namesToImport = new ArrayList<String>(); for (String declaredTypeName : importReferenceCollector.getUnqualifiedDeclaredTypes()) { importedNonQualifiedNames.add(getLastSegment(declaredTypeName)); } // add all the retained imports also to the list for (final ImportDeclaration importDeclaration : importDeclarations) { final String nameToImport = importDeclaration.getName().getFullyQualifiedName(); if (!namesToImport.contains(nameToImport)) { namesToImport.add(nameToImport); } } // handle a special case that there is a collision between a class in the same // package and a class imported from another package. In this case the class imported // from the other package should not be unqualified. This is accomplished by setting the // imports for the same package first, then later imports are recognized as collisions final String packageName = importReferenceCollector.getPackageName(); Collections.sort(cleanedQualifedNames, new QualifiedNameSorter(packageName)); for (final String qualifiedName : cleanedQualifedNames) { // already done final String correctedQualifiedName = getCorrectQualifiedName(qualifiedName); if (namesToImport.contains(correctedQualifiedName)) { continue; } // assume that it is covered by an already existing import if (!correctedQualifiedName.contains(DOT)) { continue; } final String lastSegment = getLastSegment(correctedQualifiedName); if (importedNonQualifiedNames.contains(lastSegment)) { // do not import these names to prevent collisions continue; } // if only one dot then also do not import // this is for example values.length (where values is an array) if (correctedQualifiedName.indexOf(DOT) == correctedQualifiedName.lastIndexOf(DOT)) { continue; } // prevent collisions later importedNonQualifiedNames.add(lastSegment); namesToImport.add(correctedQualifiedName); } final AST ast = compilationUnit.getAST(); final List<ImportDeclaration> newImports = new ArrayList<ImportDeclaration>(); for (final String nameToImport : namesToImport) { // don't do these ones if (inPackage(packageName, nameToImport)) { continue; } final Name name = ast.newName(nameToImport); final ImportDeclaration importDeclaration = ast.newImportDeclaration(); importDeclaration.setOnDemand(false); importDeclaration.setStatic(false); importDeclaration.setName(name); newImports.add(importDeclaration); } try { String newSource = updateSource(namesToImport, newImports, ast, importReferenceCollector.getPackageName()); // DIRTY HACK: solve an issue that if an EPackage has a sub package with the same // name that the import resolving of the subpackage goes wrong // for example the KdmModelPackage has a subpackage with the same name: KdmModelPackage // this results in this line in the source code: // kdm.KdmModelPackage.initialize(); // which is incorrect for (String qualifiedName : cleanedQualifedNames) { // find the last two segments if (!qualifiedName.contains(DOT)) { continue; } final String[] parts = DOT_PATTERN.split(qualifiedName); if (parts.length > 1) { final String part1 = parts[parts.length - 2]; final String part2 = parts[parts.length - 1]; { final String searchString = "\t" + part1 + DOT + part2 + ".initialize();"; //$NON-NLS-1$ //$NON-NLS-2$ if (newSource.contains(searchString)) { newSource = newSource.replace(searchString, "\t" + qualifiedName + ".initialize();"); //$NON-NLS-1$ //$NON-NLS-2$ } } { final String searchString = " " + part1 + DOT + part2 + ".initialize();"; //$NON-NLS-1$ //$NON-NLS-2$ if (newSource.contains(searchString)) { newSource = newSource.replace(searchString, " " + qualifiedName + ".initialize();"); //$NON-NLS-1$ //$NON-NLS-2$ } } { final String searchString = "\n" + part1 + DOT + part2 + ".initialize();"; //$NON-NLS-1$ //$NON-NLS-2$ if (newSource.contains(searchString)) { newSource = newSource.replace(searchString, "\n" + qualifiedName + ".initialize();"); //$NON-NLS-1$ //$NON-NLS-2$ } } } } return newSource; } catch (final Exception e) { throw new IllegalStateException(e); } }
From source file:org.eclipse.jdt.core.dom.ASTConverter.java
License:Open Source License
public ImportDeclaration convertImport(org.eclipse.jdt.internal.compiler.ast.ImportReference importReference) { final ImportDeclaration importDeclaration = new ImportDeclaration(this.ast); final boolean onDemand = (importReference.bits & org.eclipse.jdt.internal.compiler.ast.ASTNode.OnDemand) != 0; final char[][] tokens = importReference.tokens; int length = importReference.tokens.length; final long[] positions = importReference.sourcePositions; if (length > 1) { importDeclaration.setName(setQualifiedNameNameAndSourceRanges(tokens, positions, importReference)); } else {/*from w w w . ja v a 2s .c o m*/ final SimpleName name = new SimpleName(this.ast); name.internalSetIdentifier(new String(tokens[0])); final int start = (int) (positions[0] >>> 32); final int end = (int) (positions[0] & 0xFFFFFFFF); name.setSourceRange(start, end - start + 1); name.index = 1; importDeclaration.setName(name); if (this.resolveBindings) { recordNodes(name, importReference); } } importDeclaration.setSourceRange(importReference.declarationSourceStart, importReference.declarationEnd - importReference.declarationSourceStart + 1); importDeclaration.setOnDemand(onDemand); int modifiers = importReference.modifiers; if (modifiers != ClassFileConstants.AccDefault) { switch (this.ast.apiLevel) { case AST.JLS2_INTERNAL: importDeclaration.setFlags(importDeclaration.getFlags() | ASTNode.MALFORMED); break; default: if (modifiers == ClassFileConstants.AccStatic) { importDeclaration.setStatic(true); } else { importDeclaration.setFlags(importDeclaration.getFlags() | ASTNode.MALFORMED); } } } if (this.resolveBindings) { recordNodes(importDeclaration, importReference); } return importDeclaration; }
From source file:org.eclipse.objectteams.otdt.ui.tests.dom.rewrite.ASTRewriteFlattenerTest.java
License:Open Source License
public void testNewCuCreation() { PackageDeclaration newPack = _newAst.newPackageDeclaration(); newPack.setName(/*w w w . ja v a 2 s .com*/ _newAst.newQualifiedName(_newAst.newSimpleName("testmain"), _newAst.newSimpleName("testsub"))); ImportDeclaration newImport = _newAst.newImportDeclaration(); newImport.setName( _newAst.newQualifiedName(_newAst.newSimpleName("testpackage"), _newAst.newSimpleName("TestClass"))); newImport.setOnDemand(false); List importList = new ArrayList(); importList.add(newImport); CompilationUnit newCU = createCU(newPack, importList, null); newCU.accept(_rewriteFlattener); String actual = _rewriteFlattener.getResult(); String expected = "package testmain.testsub;import testpackage.TestClass;"; assertEquals("Wrong CU-Code", expected, actual); }
From source file:org.eclipse.objectteams.otdt.ui.tests.dom.rewrite.ASTRewriteFlattenerTest.java
License:Open Source License
public void testNewFullyCuCreation() { PackageDeclaration newPack = _newAst.newPackageDeclaration(); newPack.setName(// w ww . ja v a 2 s . co m _newAst.newQualifiedName(_newAst.newSimpleName("testmain"), _newAst.newSimpleName("testsub"))); ImportDeclaration newImport = _newAst.newImportDeclaration(); newImport.setName( _newAst.newQualifiedName(_newAst.newSimpleName("testpackage"), _newAst.newSimpleName("TestClass"))); newImport.setOnDemand(false); List importList = new ArrayList(); importList.add(newImport); int callinMappingModifier = Modifier.OT_REPLACE_CALLIN; //Callin - roleMethodSpec - Parameter SingleVariableDeclaration roleMethodSpecParameter = createMethodParameter(0, "Integer", null, "roleInteger", 0, null); List roleMethodParameters = new ArrayList(); roleMethodParameters.add(roleMethodSpecParameter); //Callin - roleMethodSpec MethodSpec roleMethodSpec = createMethodSpec("roleMethod1", PrimitiveType.INT, roleMethodParameters, true); //Callin - baseMethodSpec - Parameter SingleVariableDeclaration baseMethodSpecParameter = createMethodParameter(0, "Integer", null, "integer", 0, null); List baseMethodParameters = new ArrayList(); baseMethodParameters.add(baseMethodSpecParameter); //Callin - baseMethodSpec(s) MethodSpec baseMethodSpec = createMethodSpec("baseMethod1", PrimitiveType.INT, baseMethodParameters, true); List baseMethods = new ArrayList(); baseMethods.add(baseMethodSpec); //Callin - ParameterMapping SimpleName expressionName1 = (SimpleName) createExpression("integer"); ParameterMapping newParameterMappingInt = createParameterMapping(expressionName1, "roleInteger", "<-", false); SimpleName expressionName2 = (SimpleName) createExpression("result"); ParameterMapping newParameterMappingRes = createParameterMapping(expressionName2, "result", "->", true); List paramMappings = new ArrayList(); paramMappings.add(newParameterMappingInt); paramMappings.add(newParameterMappingRes); //build CallinMapping CallinMappingDeclaration newCallinMapping = createCallinMappingDeclaration(null, callinMappingModifier, roleMethodSpec, baseMethods, paramMappings); List roleBodyDecl = new ArrayList(); roleBodyDecl.add(newCallinMapping); RoleTypeDeclaration role = createRole(null, 1, "GeneratedRoleClass", "GeneratedBaseClass", "GeneratedTeamClass", null, null, false, roleBodyDecl); List typeBodyDecl = new ArrayList(); typeBodyDecl.add(role); TypeDeclaration newTypeDecl = createTeam(null, (Modifier.PUBLIC | Modifier.OT_TEAM), false, false, "GeneratedClass", null, null, typeBodyDecl); List typeList = new ArrayList(); typeList.add(newTypeDecl); CompilationUnit newCU = createCU(newPack, importList, typeList); newCU.accept(_rewriteFlattener); String cUString = "package testmain.testsub;import testpackage.TestClass;public team class GeneratedClass {"; String roleString = "public class GeneratedRoleClass playedBy GeneratedBaseClass {"; String bodyDeclString = "int roleMethod1(Integer roleInteger) <- replace int baseMethod1(Integer integer)"; String paramMappingString = " with {\n" + " roleInteger <- integer,\n" + " result -> result\n" + "}}}"; String actual = _rewriteFlattener.getResult(); String expected = cUString + roleString + bodyDeclString + paramMappingString; assertEquals("Wrong CU-Code", expected, actual); }
From source file:org.jboss.ide.eclipse.as.ui.mbeans.wizards.pages.NewMessageDrivenBeanWizardPage.java
License:Open Source License
public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException { super.createType(monitor); IType createdBeanType = getCreatedType(); ICompilationUnit beanUnit = createdBeanType.getCompilationUnit(); Document doc = new Document(beanUnit.getSource()); ASTParser c = ASTParser.newParser(AST.JLS3); c.setSource(beanUnit.getSource().toCharArray()); c.setResolveBindings(true);//from ww w . j av a 2s . c o m CompilationUnit beanAstUnit = (CompilationUnit) c.createAST(null); AST ast = beanAstUnit.getAST(); beanAstUnit.recordModifications(); ImportDeclaration importDecl = ast.newImportDeclaration(); importDecl.setOnDemand(false); importDecl.setName(ast.newName(new String[] { "javax", "ejb", "MessageDriven" })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ beanAstUnit.imports().add(importDecl); MarkerAnnotation sessionAnnotation = ast.newMarkerAnnotation(); sessionAnnotation.setTypeName(ast.newSimpleName("MessageDriven")); //$NON-NLS-1$ TypeDeclaration type = (TypeDeclaration) beanAstUnit.types().get(0); type.modifiers().add(sessionAnnotation); TextEdit edit = beanAstUnit.rewrite(doc, null); try { UndoEdit undo = edit.apply(doc); String source = doc.get(); beanUnit.getBuffer().setContents(source); beanUnit.getBuffer().save(monitor, true); } catch (BadLocationException e) { e.printStackTrace(); } }
From source file:org.jboss.ide.eclipse.as.ui.mbeans.wizards.pages.NewSessionBeanWizardPage.java
License:Open Source License
public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException { super.createType(monitor); IType createdBeanType = getCreatedType(); // //from w w w . j av a2 s .c o m // AST ast = new AST(); // MarkerAnnotation annotation = ast.newMarkerAnnotation(); // annotation.setTypeName(ast.newSimpleName("Stateless")); // beanType.getCompilationUnit().becomeWorkingCopy() ICompilationUnit remoteInterfaceUnit = createRemoteInterface(monitor); ICompilationUnit beanUnit = createdBeanType.getCompilationUnit(); Document doc = new Document(beanUnit.getSource()); ASTParser c = ASTParser.newParser(AST.JLS3); c.setSource(beanUnit.getSource().toCharArray()); c.setResolveBindings(true); CompilationUnit beanAstUnit = (CompilationUnit) c.createAST(null); AST ast = beanAstUnit.getAST(); beanAstUnit.recordModifications(); ImportDeclaration importDecl = ast.newImportDeclaration(); importDecl.setName(ast.newName(new String[] { "javax", "ejb", beanType })); //$NON-NLS-1$ //$NON-NLS-2$ importDecl.setOnDemand(false); beanAstUnit.imports().add(importDecl); importDecl = ast.newImportDeclaration(); String pkgElements[] = remoteInterfacePackage.split("\\."); //$NON-NLS-1$ String fullImport[] = new String[pkgElements.length + 1]; System.arraycopy(pkgElements, 0, fullImport, 0, pkgElements.length); fullImport[fullImport.length - 1] = remoteInterfaceName; importDecl.setName(ast.newName(fullImport)); importDecl.setOnDemand(false); beanAstUnit.imports().add(importDecl); MarkerAnnotation sessionAnnotation = ast.newMarkerAnnotation(); sessionAnnotation.setTypeName(ast.newSimpleName(beanType)); TypeDeclaration type = (TypeDeclaration) beanAstUnit.types().get(0); type.modifiers().add(sessionAnnotation); type.superInterfaceTypes().add(ast.newSimpleType(ast.newSimpleName(remoteInterfaceName))); TextEdit edit = beanAstUnit.rewrite(doc, null); try { UndoEdit undo = edit.apply(doc); String source = doc.get(); beanUnit.getBuffer().setContents(source); beanUnit.getBuffer().save(monitor, true); } catch (MalformedTreeException e) { IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, MessageFormat .format(Messages.NewSessionBeanWizardPage_could_not_create_type, beanUnit.getElementName()), e); Activator.getDefault().getLog().log(status); } catch (BadLocationException e) { IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, MessageFormat .format(Messages.NewSessionBeanWizardPage_could_not_create_type, beanUnit.getElementName()), e); //$NON-NLS-1$ Activator.getDefault().getLog().log(status); } }
From source file:org.jboss.tools.ws.creation.core.commands.ImplementationClassCreationCommand.java
License:Open Source License
@SuppressWarnings("unchecked") private void addImportsToImplementationClass(CompilationUnit implCU, CompilationUnit serviceCU, String serviceName) {/* w w w .j a v a2 s . co m*/ List<ImportDeclaration> imports = getImportsWithoutJaxwsAnnotation(serviceCU); AST implAST = implCU.getAST(); // add imports for implementation class for (ImportDeclaration id : imports) { ImportDeclaration newId = implAST.newImportDeclaration(); newId.setName(implAST.newName(id.getName().getFullyQualifiedName())); implCU.imports().add(newId); } // import port type interface ImportDeclaration importDec = implAST.newImportDeclaration(); importDec.setName(implAST.newName(serviceCU.getPackage().getName().toString())); importDec.setOnDemand(true); implCU.imports().add(importDec); // importDec = implAST.newImportDeclaration(); // importDec.setName(implAST.newName(LOGGER_CLASS_FULLNAME)); // implCU.imports().add(importDec); // import jaxws WebService importDec = implAST.newImportDeclaration(); // hardcode here? importDec.setName(implAST.newName(ANNOTATION_WEB_SERVICE_FULLNAME)); implCU.imports().add(importDec); }