List of usage examples for org.eclipse.jdt.core ICompilationUnit getWorkingCopy
ICompilationUnit getWorkingCopy(IProgressMonitor monitor) throws JavaModelException;
From source file:com.idega.eclipse.ejbwizards.IBOEntityCreator.java
License:Open Source License
protected void generateCode() throws JavaModelException { IProgressMonitor monitor = new NullProgressMonitor(); monitor.beginTask("Begin creation", IProgressMonitor.UNKNOWN); //$NON-NLS-1$ IResource idoEntityResource = getType().getResource(); IPackageFragment pack = getType().getPackageFragment(); ICompilationUnit unit = getType().getCompilationUnit(); String typeName = idoEntityResource.getName().substring(0, idoEntityResource.getName().lastIndexOf("Bean")); String[] interfaces = getType().getSuperInterfaceTypeSignatures(); ICompilationUnit interfaceUnit = pack.createCompilationUnit(typeName + ".java", "", true, //$NON-NLS-1$//$NON-NLS-2$ new SubProgressMonitor(monitor, 2)); ICompilationUnit interfaceHomeUnit = pack.createCompilationUnit(typeName + "Home.java", "", true, //$NON-NLS-1$//$NON-NLS-2$ new SubProgressMonitor(monitor, 2)); ICompilationUnit homeImplUnit = pack.createCompilationUnit(typeName + "HomeImpl.java", "", true, //$NON-NLS-1$//$NON-NLS-2$ new SubProgressMonitor(monitor, 2)); try {/* w ww. j ava 2 s . c o m*/ createInterface(monitor, interfaceUnit.getWorkingCopy(monitor), pack.getElementName(), typeName, interfaces); createHomeInterface(monitor, interfaceHomeUnit.getWorkingCopy(monitor), pack.getElementName(), typeName); createHomeImplementation(monitor, homeImplUnit.getWorkingCopy(monitor), pack.getElementName(), typeName); addInterfaceToBean(monitor, unit.getWorkingCopy(monitor), typeName); } catch (MalformedTreeException e) { e.printStackTrace(); } catch (BadLocationException e) { e.printStackTrace(); } monitor.done(); }
From source file:com.idega.eclipse.ejbwizards.IDOEntityCreator.java
License:Open Source License
protected void generateCode() throws JavaModelException { IProgressMonitor monitor = new NullProgressMonitor(); monitor.beginTask("Begin creation", IProgressMonitor.UNKNOWN); //$NON-NLS-1$ IResource idoEntityResource = getType().getResource(); IPackageFragment pack = getType().getPackageFragment(); ICompilationUnit unit = getType().getCompilationUnit(); String typeName = idoEntityResource.getName().substring(0, idoEntityResource.getName().lastIndexOf("BMPBean")); String[] interfaces = getType().getSuperInterfaceTypeSignatures(); ICompilationUnit interfaceUnit = pack.createCompilationUnit(typeName + ".java", "", true, //$NON-NLS-1$//$NON-NLS-2$ new SubProgressMonitor(monitor, 2)); ICompilationUnit interfaceHomeUnit = pack.createCompilationUnit(typeName + "Home.java", "", true, //$NON-NLS-1$//$NON-NLS-2$ new SubProgressMonitor(monitor, 2)); ICompilationUnit homeImplUnit = pack.createCompilationUnit(typeName + "HomeImpl.java", "", true, //$NON-NLS-1$//$NON-NLS-2$ new SubProgressMonitor(monitor, 2)); try {/*from www .j ava 2s. co m*/ createInterface(monitor, interfaceUnit.getWorkingCopy(monitor), pack.getElementName(), typeName, interfaces); createHomeInterface(monitor, interfaceHomeUnit.getWorkingCopy(monitor), pack.getElementName(), typeName); createHomeImplementation(monitor, homeImplUnit.getWorkingCopy(monitor), pack.getElementName(), typeName); addInterfaceToBean(monitor, unit.getWorkingCopy(monitor), typeName); } catch (MalformedTreeException e) { e.printStackTrace(); } catch (BadLocationException e) { e.printStackTrace(); } monitor.done(); }
From source file:com.iw.plugins.spindle.ui.wizards.factories.ClassFactory.java
License:Mozilla Public License
private void createType(IProgressMonitor monitor) throws CoreException, InterruptedException { if (monitor == null) { monitor = new NullProgressMonitor(); }// w w w .j a v a 2 s .c om monitor.beginTask(UIPlugin.getString("ClassFactory.operationdesc", fTypeName), 10); ICompilationUnit createdWorkingCopy = null; try { IPackageFragmentRoot root = fPackageFragmentyRoot; IPackageFragment pack = fPackageFragment; if (pack == null) { pack = root.getPackageFragment(""); //$NON-NLS-1$ } if (!pack.exists()) { String packName = pack.getElementName(); pack = root.createPackageFragment(packName, true, null); } monitor.worked(1); String clName = fTypeName; boolean isInnerClass = false; IType createdType; ImportsManager imports; int indent = 0; String lineDelimiter = System.getProperty("line.separator", "\n"); ICompilationUnit parentCU = pack.createCompilationUnit(clName + ".java", "", false, new SubProgressMonitor(monitor, 2)); // create a working copy with a new owner createdWorkingCopy = parentCU.getWorkingCopy(null); // use the compiler template a first time to read the imports String content = CodeGeneration.getCompilationUnitContent(createdWorkingCopy, null, "", lineDelimiter); //$NON-NLS-1$ if (content != null) createdWorkingCopy.getBuffer().setContents(content); imports = new ImportsManager(createdWorkingCopy); // add an import that will be removed again. Having this import solves // 14661 imports.addImport(JavaModelUtil.concatenateName(pack.getElementName(), fTypeName)); String typeContent = constructTypeStub(imports, lineDelimiter); String cuContent = constructCUContent(parentCU, typeContent, lineDelimiter); createdWorkingCopy.getBuffer().setContents(cuContent); createdType = createdWorkingCopy.getType(clName); if (monitor.isCanceled()) { throw new InterruptedException(); } // add imports for superclass/interfaces, so types can be resolved // correctly ICompilationUnit cu = createdType.getCompilationUnit(); boolean needsSave = !cu.isWorkingCopy(); imports.create(needsSave, new SubProgressMonitor(monitor, 1)); JavaModelUtil.reconcile(cu); if (monitor.isCanceled()) { throw new InterruptedException(); } // set up again imports = new ImportsManager(imports.getCompilationUnit(), imports.getAddedTypes()); createTypeMembers(createdType, imports, new SubProgressMonitor(monitor, 1)); // add imports imports.create(needsSave, new SubProgressMonitor(monitor, 1)); removeUnusedImports(cu, imports.getAddedTypes(), needsSave); JavaModelUtil.reconcile(cu); ISourceRange range = createdType.getSourceRange(); IBuffer buf = cu.getBuffer(); String originalContent = buf.getText(range.getOffset(), range.getLength()); String formattedContent = CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, originalContent, indent, null, lineDelimiter, pack.getJavaProject()); buf.replace(range.getOffset(), range.getLength(), formattedContent); // String fileComment = getFileComment(cu); // if (fileComment != null && fileComment.length() > 0) // { // buf.replace(0, 0, fileComment + lineDelimiter); // } cu.commitWorkingCopy(false, new SubProgressMonitor(monitor, 1)); if (createdWorkingCopy != null) { fCreatedType = (IType) createdType.getPrimaryElement(); } else { fCreatedType = createdType; } } finally { if (createdWorkingCopy != null) { createdWorkingCopy.discardWorkingCopy(); } monitor.done(); } }
From source file:com.motorola.studio.android.model.ActivityBasedOnTemplate.java
License:Apache License
/** * Creates the Java Class file based on text template file * //www .j a v a2 s.c o m * @param sourcePath The path to the file * @param monitor The progress monitor * @throws JavaModelException * @throws AndroidException */ @SuppressWarnings({ "rawtypes", "unchecked" }) protected void createJavaClassFileFromTemplate(String[] sourcePath, IProgressMonitor monitor) throws JavaModelException, AndroidException { //only one class supported for (int i = 0; i < sourcePath.length; i++) { String loadedTemplate = EclipseUtils.readEmbeddedResource(CodeUtilsActivator.getDefault().getBundle(), sourcePath[i]); String packageName = getPackageFragment().getElementName(); loadedTemplate = loadedTemplate.replaceAll(CLASS_REPLACE_TAG, getName()); loadedTemplate = loadedTemplate.replaceAll(PACKAGE_REPLACE_TAG, packageName); loadedTemplate = loadedTemplate.replaceAll("#FILL_PARENT_LPARAM#", getApiVersion() > 7 ? "MATCH_PARENT" : "FILL_PARENT"); try { loadedTemplate = loadedTemplate.replaceAll("#ManifestPackageName#", //$NON-NLS-1$ getManifestPackageName(getProject())); } catch (CoreException e) { throw new AndroidException("Failed to get manifest file to add import from R", e); //$NON-NLS-1$ } if ((sample != null) && sample.equals(ActivityBasedOnTemplate.DATABASE_LIST_SAMPLE_LOCALIZED)) { collector = getDatabaseSampleActivityParametersWizardCollector(); if (collector != null) { collector.setDatabaseName(this.collectorDatabaseName); collector.setTable(this.collectorTable); collector.setSelectedColumns(collectorColumnList); collector.setSqlOpenHelperClassName(getSqlOpenHelperClassName()); collector.setSqlOpenHelperPackageName(getSqlOpenHelperPackageName()); collector.setCreateOpenHelper(isCreateOpenHelper()); //using Database list sample - it is an special case because it get data from an specific .db table loadedTemplate = loadedTemplate.replaceAll("#dbName#", collector.getDatabaseName()); //$NON-NLS-1$ loadedTemplate = loadedTemplate.replaceAll("#tableName#", collector.getTableName()); //$NON-NLS-1$ loadedTemplate = loadedTemplate.replaceAll("#tableNameUpperCase#", collector.getTableName() //$NON-NLS-1$ .toUpperCase()); loadedTemplate = loadedTemplate.replaceAll("#tableNameLowerCase#", collector.getTableName() //$NON-NLS-1$ .toLowerCase()); loadedTemplate = loadedTemplate.replaceAll("#columsNames#", collector.getColumnsNames()); //$NON-NLS-1$ loadedTemplate = loadedTemplate.replaceAll("#constColumnsNames#", //$NON-NLS-1$ collector.getConstColumnsNames()); loadedTemplate = loadedTemplate.replaceAll("#columnGetValues#", collector.getCursorValues()); //$NON-NLS-1$ loadedTemplate = loadedTemplate.replaceAll("#columnAddRows#", collector.getAddColumnsToRow()); //$NON-NLS-1$ loadedTemplate = loadedTemplate.replaceAll("#sqlOpenHelperName#", //$NON-NLS-1$ getSqlOpenHelperClassName()); loadedTemplate = loadedTemplate.replaceAll("#imports#", collector.getImports()); //$NON-NLS-1$ loadedTemplate = loadedTemplate.replaceAll("#getReadableDatabase#", //$NON-NLS-1$ collector.getReadableDatabase()); if (isCreateOpenHelper()) { collector.createSqlOpenHelper(getProject(), monitor); } } } //replace the main activity of the project, first used by action_bar template try { //assume mainActivity be the activity we are creating (if the project has no main activity). Try to find the real main activity if the isMainActivity flag is false. String mainActivityName = getName(); if (!isMainActivity) { ActivityNode mainActivityNode = AndroidProjectManifestFile.getFromProject(getProject()) .getMainActivity(); if (mainActivityNode != null) { mainActivityName = mainActivityNode.getNodeProperties().get("android:name"); //remove a possible '.' that activities may contain before the name if ((mainActivityName.length() > 0) && (mainActivityName.charAt(0) == '.')) { mainActivityName = mainActivityName.substring(1, mainActivityName.length()); } } } loadedTemplate = loadedTemplate.replaceAll(MAIN_ACTIVITY_REPLACE_TAG, mainActivityName); } catch (CoreException e) { StudioLogger.error("Could not get Android Manifest File from project."); } loadedTemplate = replaceResourceNames(loadedTemplate); IPackageFragment targetPackage = getPackageFragmentRoot() .getPackageFragment(getPackageFragment().getElementName()); if (!targetPackage.exists()) { getPackageFragmentRoot().createPackageFragment(targetPackage.getElementName(), true, monitor); } /* * Create activity class. Only the first src resource will become the Activity subclass. * The other classes will be copied AS IS */ String resourceName = i == 0 ? getName() + JAVA_EXTENSION : Path.fromPortableString(sourcePath[i]).lastSegment(); ICompilationUnit cu = targetPackage.createCompilationUnit(resourceName, loadedTemplate, true, monitor); //indent activity class try { ICompilationUnit workingCopy = cu.getWorkingCopy(monitor); IDocument document = new DocumentAdapter(workingCopy.getBuffer()); //get project indentation configuration Map mapOptions = JavaCore.create(getProject()).getOptions(true); //changes to be applyed to the document TextEdit textEdit = CodeFormatterUtil.format2( CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS, document.get(), 0, System.getProperty("line.separator"), mapOptions); //$NON-NLS-1$ workingCopy.applyTextEdit(textEdit, monitor); workingCopy.reconcile(ICompilationUnit.NO_AST, false, null, null); workingCopy.commitWorkingCopy(true, monitor); workingCopy.discardWorkingCopy(); } catch (Exception ex) { //do nothing - indentation fails } } }
From source file:de.akra.idocit.java.services.JavaInterfaceParserTest.java
License:Apache License
/** * Tests the conversion of existing Javadoc to {@link Documentation}s. The * documentations must also be assigned to the right {@link SignatureElements}, e.g. * "@param ..." to a method's input {@link Parameter} etc. * //from ww w . j a v a 2s. co m * @throws Exception */ @Test public void testJavadocConversion() throws Exception { String testFileName = AllIDocItJavaTests.SOURCE_DIR + "JavaInterfaceParser.java"; IFile iFile = TestUtils.makeIFileFromFileName(testFileName); ICompilationUnit iCompilationUnit = JavaCore.createCompilationUnitFrom(iFile); Assert.assertNotNull(iCompilationUnit); parser.setSource(iCompilationUnit.getWorkingCopy(null)); CompilationUnit cu = (CompilationUnit) parser.createAST(null); JavaInterfaceParser iParser = new JavaInterfaceParser(cu, testFileName, delimiters); InterfaceArtifact actualArtifact = iParser.parse(JavadocParser.INSTANCE); JavaInterfaceArtifact expectedArtifact = createExpectedArtifact(testFileName, cu); Assert.assertEquals(TestUtils.toStringWithoutId(expectedArtifact), TestUtils.toStringWithoutId(actualArtifact)); }
From source file:de.akra.idocit.java.services.JavaInterfaceParserTest.java
License:Apache License
/** * Parses the file <code>fileName</code>, prints the structure and returns the * structure as string./*from www .j a va2 s. c o m*/ * * @param fileName * @return a simple string representation of the class structure. * @throws FileNotFoundException * @throws IOException * @throws ParserConfigurationException * @throws SAXException * @throws CoreException * @throws ParsingException */ private String testParseWith(String fileName) throws FileNotFoundException, IOException, SAXException, ParserConfigurationException, CoreException, ParsingException { IFile iFile = TestUtils.makeIFileFromFileName(fileName); ICompilationUnit iCompilationUnit = JavaCore.createCompilationUnitFrom(iFile); Assert.assertNotNull(iCompilationUnit); parser.setSource(iCompilationUnit.getWorkingCopy(null)); CompilationUnit cu = (CompilationUnit) parser.createAST(null); JavaInterfaceParser iParser = new JavaInterfaceParser(cu, fileName, delimiters); InterfaceArtifact artifact = iParser.parse(JavadocParser.INSTANCE); StringBuffer hierarchy = new StringBuffer(); TestUtils.buildHierarchy(hierarchy, artifact, 0); logger.log(Level.FINER, fileName); logger.log(Level.FINER, hierarchy.toString()); return hierarchy.toString(); }
From source file:de.akra.idocit.java.services.JavaParser.java
License:Apache License
/** * {@inheritDoc }/*from w w w .j a va 2 s. co m*/ * * @source_format Java and Javadoc according to their current specifications<br/> * - <a href="http://docs.oracle.com/javase/specs/">Java</a> <br/> * - <a href= * "http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html" * >Javadoc</a> * * @instrument To parse the Java and Javadoc code, the parser provided by the <a * href="http://www.eclipse.org/jdt/">Eclipse Java Development Tools</a> * is used. * * @param iFile * [SOURCE] (ERROR DOC) * * @return [OBJECT] * * @throws Exception * @see de.akra.idocit.core.extensions.Parser#parse(IFile) * @thematicgrid Parsing Operations */ @Override public InterfaceArtifact parse(IFile iFile) throws Exception { logger.log(Level.INFO, "parse file: " + iFile.getFullPath().toFile().getAbsolutePath()); final ICompilationUnit iCompilationUnit = JavaCore.createCompilationUnitFrom(iFile); if (iCompilationUnit == null) { logger.log(Level.SEVERE, "Can not create ICompilationUnit from " + iFile.getLocation().toFile().getAbsolutePath()); return InterfaceArtifact.NOT_SUPPORTED_ARTIFACT; } final ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setKind(ASTParser.K_COMPILATION_UNIT); parser.setSource(iCompilationUnit.getWorkingCopy(null)); parser.setResolveBindings(true); // bindings are needed for object reflection parser.setBindingsRecovery(true); final CompilationUnit compilationUnit = (CompilationUnit) parser .createAST(Job.getJobManager().createProgressGroup()); compilationUnit.recordModifications(); de.akra.idocit.java.services.JavaInterfaceParser jInterfaceParser = new JavaInterfaceParser(compilationUnit, compilationUnit.getJavaElement().getElementName(), delimiters); final InterfaceArtifact artifact = jInterfaceParser.parse(getJavadocParser()); return artifact; }
From source file:edu.illinois.compositerefactorings.refactorings.NewClassCreator.java
License:Open Source License
public List<ResourceChange> createTopLevelParameterObject() throws CoreException { List<ResourceChange> changes = new ArrayList<ResourceChange>(); ICompilationUnit unit = getPackageFragment() .getCompilationUnit(getClassName() + JavaModelUtil.DEFAULT_CU_SUFFIX); Assert.isTrue(!unit.exists());//from ww w . j a va 2s.c o m IJavaProject javaProject = unit.getJavaProject(); ICompilationUnit workingCopy = unit.getWorkingCopy(null); try { // create stub with comments and dummy type String lineDelimiter = StubUtility.getLineDelimiterUsed(javaProject); String fileComment = getFileComment(workingCopy, lineDelimiter); String typeComment = getTypeComment(workingCopy, lineDelimiter); String content = CodeGeneration.getCompilationUnitContent(workingCopy, fileComment, typeComment, "class " + getClassName() + "{}", lineDelimiter); //$NON-NLS-1$ //$NON-NLS-2$ workingCopy.getBuffer().setContents(content); CompilationUnitRewrite cuRewrite = new CompilationUnitRewrite(workingCopy); ASTRewrite rewriter = cuRewrite.getASTRewrite(); CompilationUnit root = cuRewrite.getRoot(); AST ast = cuRewrite.getAST(); ImportRewrite importRewrite = cuRewrite.getImportRewrite(); if (fSuperclassType != null) { importRewrite.addImport(fSuperclassType.resolveBinding()); } // retrieve&replace dummy type with real class ListRewrite types = rewriter.getListRewrite(root, CompilationUnit.TYPES_PROPERTY); ASTNode dummyType = (ASTNode) types.getOriginalList().get(0); TypeDeclaration classDeclaration = createClassDeclaration(getClassName(), cuRewrite); classDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD)); Javadoc javadoc = (Javadoc) dummyType.getStructuralProperty(TypeDeclaration.JAVADOC_PROPERTY); rewriter.set(classDeclaration, TypeDeclaration.JAVADOC_PROPERTY, javadoc, null); types.replace(dummyType, classDeclaration, null); // Apply rewrites and discard workingcopy // Using CompilationUnitRewrite.createChange() leads to strange // results String charset = ResourceUtil.getFile(unit).getCharset(false); Document document = new Document(content); try { rewriter.rewriteAST().apply(document); TextEdit rewriteImports = importRewrite.rewriteImports(null); rewriteImports.apply(document); } catch (BadLocationException e) { throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), RefactoringCoreMessages.IntroduceParameterObjectRefactoring_parameter_object_creation_error, e)); } String docContent = document.get(); CreateCompilationUnitChange compilationUnitChange = new CreateCompilationUnitChange(unit, docContent, charset); changes.add(compilationUnitChange); } finally { workingCopy.discardWorkingCopy(); } return changes; }
From source file:org.assertj.eclipse.assertions.generator.internal.text.SourceFormatter.java
License:Apache License
private ICompilationUnit createWorkingCopy(ICompilationUnit compilationUnit, IProgressMonitor pm) throws JavaModelException { if (!compilationUnit.isOpen()) { compilationUnit.open(pm);/*from ww w . j a v a 2 s . c o m*/ } return compilationUnit.getWorkingCopy(pm); }
From source file:org.dyno.visual.swing.parser.DefaultSourceParser.java
License:Open Source License
public ICompilationUnit generate(WidgetAdapter root, IProgressMonitor monitor) { try {/*from ww w . java2 s. c o m*/ IParser parser = (IParser) root.getAdapter(IParser.class); if (parser == null) return null; ICompilationUnit unit = root.getCompilationUnit(); ICompilationUnit copy = unit.getWorkingCopy(monitor); IType type = getUnitMainType(copy); if (type != null) { ImportRewrite imports = createImportRewrite(copy); boolean success = parser.generateCode(type, imports, monitor); if (!success) return null; removeRemovedComponent(root, monitor, unit, type); createPreferredLnf(root, monitor, type, imports); if (success) { TextEdit edit = imports.rewriteImports(monitor); JavaUtil.applyEdit(copy, edit, true, monitor); } if (copy.isWorkingCopy()) { copy.commitWorkingCopy(true, monitor); copy.discardWorkingCopy(); } IWorkbenchPartSite site = getEditorSite(); if (site != null) { OrganizeImportsAction action = new OrganizeImportsAction(site); action.run(unit); } type = getUnitMainType(unit); rename(type, root); if (unit.isWorkingCopy()) { unit.commitWorkingCopy(true, monitor); } return unit; } else return null; } catch (Exception e) { ParserPlugin.getLogger().error(e); return null; } }