List of usage examples for org.eclipse.jdt.core.formatter CodeFormatter format
public abstract TextEdit format(int kind, String source, int offset, int length, int indentationLevel, String lineSeparator);
source, and returns a text edit that correspond to the difference between the given string and the formatted string. From source file:ac.at.tuwien.dsg.uml.statemachine.export.transformation.util.JavaClassOutputter.java
License:Open Source License
public static void outputFile(ITransformContext context, Document doc, String filename, String generationStrategyName, String stateMachineName) { //generate CLass output file IResource res = (IResource) context.getTargetContainer(); IPath targetPath = res.getLocation(); CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(null); String code = doc.get();// ww w .j ava2 s .c o m TextEdit textEdit = codeFormatter.format(CodeFormatter.K_UNKNOWN, code, 0, code.length(), 0, null); try { //unsure why but sometimes formatted is null if (textEdit != null) { textEdit.apply(doc); } else { //usually errors appear due to spaces or illegal characters in property names IOException exception = new IOException("Generated document has formatting errors: \n" + code); throw new UncheckedIOException("Generated document has formatting errors: \n" + code, exception); } File myFile = new File(filename); PrintWriter fw; try { fw = new PrintWriter(myFile); fw.write("/* Generated by " + generationStrategyName + " from state diagram " + stateMachineName + " */ \n\n"); for (String importString : defaultImports) { fw.write("import " + importString + ";"); fw.write("\n"); } fw.write("\n"); fw.write(doc.get()); fw.flush(); fw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (MalformedTreeException e) { e.printStackTrace(); } catch (BadLocationException e) { e.printStackTrace(); } }
From source file:ac.at.tuwien.dsg.uml.stereotype.export.transformation.util.JavaClassOutputter.java
License:Open Source License
public static void outputFile(ITransformContext context, IDOMNode content) { //generate CLass output file IResource res = (IResource) context.getTargetContainer(); IPath targetPath = res.getLocation(); String filename = targetPath.toOSString() + File.separatorChar + content.getName() + ".java"; //format Code String code = content.getContents(); CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(null); TextEdit textEdit = codeFormatter.format(CodeFormatter.K_UNKNOWN, code, 0, code.length(), 0, null); IDocument doc = new Document(code); try {// w ww . j av a 2s . c o m //unsure why but sometimes formatted is nu if (textEdit != null) { textEdit.apply(doc); } else { //usually errors appear due to spaces or illegal characters in property names IOException exception = new IOException("Generated document has formatting errors: \n" + code); throw new UncheckedIOException("Generated document has formatting errors: \n" + code, exception); } File myFile = new File(filename); PrintWriter fw; try { fw = new PrintWriter(myFile); for (String importString : defaultImports) { fw.write("import " + importString + ";"); fw.write("\n"); } fw.write(doc.get()); fw.flush(); fw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (MalformedTreeException e) { e.printStackTrace(); } catch (BadLocationException e) { e.printStackTrace(); } }
From source file:com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.java
License:Open Source License
private static String format(IProject project, String contents, IPath to) { String name = to.lastSegment(); if (name.endsWith(DOT_XML)) { XmlFormatStyle formatStyle = EclipseXmlPrettyPrinter.getForFile(to); EclipseXmlFormatPreferences prefs = EclipseXmlFormatPreferences.create(); return EclipseXmlPrettyPrinter.prettyPrint(contents, prefs, formatStyle, null); } else if (name.endsWith(DOT_JAVA)) { Map<?, ?> options = null; if (project != null && project.isAccessible()) { try { IJavaProject javaProject = BaseProjectHelper.getJavaProject(project); if (javaProject != null) { options = javaProject.getOptions(true); }// w ww .ja v a 2s. c o m } catch (CoreException e) { AdtPlugin.log(e, null); } } if (options == null) { options = JavaCore.getOptions(); } CodeFormatter formatter = ToolFactory.createCodeFormatter(options); try { IDocument doc = new org.eclipse.jface.text.Document(); // format the file (the meat and potatoes) doc.set(contents); TextEdit edit = formatter.format( CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS, contents, 0, contents.length(), 0, null); if (edit != null) { edit.apply(doc); } return doc.get(); } catch (Exception e) { AdtPlugin.log(e, null); } } return contents; }
From source file:com.google.gdt.eclipse.core.TypeCreator.java
License:Open Source License
private String formatJava(IType type) throws JavaModelException { String source = type.getCompilationUnit().getSource(); CodeFormatter formatter = ToolFactory.createCodeFormatter(type.getJavaProject().getOptions(true)); TextEdit formatEdit = formatter.format(CodeFormatterFlags.getFlagsForCompilationUnitFormat(), source, 0, source.length(), 0, lineDelimiter); if (formatEdit == null) { CorePluginLog.logError("Could not format source for " + type.getCompilationUnit().getElementName()); return source; }//w w w. j av a 2 s.c o m Document document = new Document(source); try { formatEdit.apply(document); source = document.get(); } catch (BadLocationException e) { CorePluginLog.logError(e); } source = Strings.trimLeadingTabsAndSpaces(source); return source; }
From source file:com.iw.plugins.spindle.ui.wizards.factories.ClassFactory.java
License:Mozilla Public License
/** * Format an entire Java source file//w w w . j av a2 s. c o m * * @param sourceString * entire file as one unformatted String * @return formatted String */ public static String formatJava(String sourceString, int initialIndentationLevel, String lineDelim) { String ret = sourceString; DefaultCodeFormatterOptions dcfo = DefaultCodeFormatterOptions.getJavaConventionsSettings(); dcfo.line_separator = lineDelim; CodeFormatter cformatter = ToolFactory.createCodeFormatter(dcfo.getMap()); TextEdit te = cformatter.format(CodeFormatter.K_COMPILATION_UNIT, sourceString, 0, sourceString.length(), initialIndentationLevel, lineDelim); IDocument l_doc = new Document(sourceString); try { te.apply(l_doc); } catch (MalformedTreeException e) { // not fatal, since we still have our original contents UIPlugin.warn(e); } catch (BadLocationException e) { // not fatal, since we still have our original contents UIPlugin.warn(e); } String maybe = l_doc.get(); // in case formatting fails, we'll just return what we got if (!didFormatChoke(maybe)) { ret = maybe; } else { UIPlugin.warn("Java formatter choked"); //TODO choked } return ret + lineDelim; // dunno why we add the extra, but we did }
From source file:com.motorola.studio.android.model.java.JavaClass.java
License:Apache License
/** * Gets the class content//from ww w .ja va 2 s . co m * * @return an IDocument object containing the class content */ public IDocument getClassContent() throws AndroidException { String content = compUnit.toString(); document = new Document(content); // Formats the code using the Eclipse settings CodeFormatter codeFormatter = ToolFactory .createCodeFormatter(DefaultCodeFormatterConstants.getEclipseDefaultSettings()); TextEdit textEdit = codeFormatter.format( CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS, content, 0, content.length(), 0, null); try { textEdit.apply(document); } catch (MalformedTreeException e) { String errMsg = NLS.bind(CodeUtilsNLS.EXC_JavaClass_ErrorFormattingSourceCode, className); StudioLogger.error(JavaClass.class, errMsg, e); throw new AndroidException(errMsg); } catch (BadLocationException e) { String errMsg = NLS.bind(CodeUtilsNLS.EXC_JavaClass_ErrorFormattingSourceCode, className); StudioLogger.error(JavaClass.class, errMsg, e); throw new AndroidException(errMsg); } addComments(); return document; }
From source file:com.spidasoftware.EclipseFormatter.JavaFormat.java
License:Apache License
public void format(String fileName, String code) { CodeFormatter cf = initializeFormatter(); TextEdit te = cf.format(CodeFormatter.K_UNKNOWN, code, 0, code.length(), 0, System.getProperty("line.separator")); IDocument dc = new Document(code.toString()); if (te == null || code.length() == 0) { log.info("!!! Could not format " + fileName + " !!!"); } else {/*from w w w. j a v a2s . com*/ PrintWriter out = null; try { te.apply(dc); out = new PrintWriter(new FileWriter(fileName)); out.println(dc.get()); log.info("*** Java standard formatting conventions have been applied to " + fileName + " ***"); correctlyFormatted = true; } catch (MalformedTreeException e) { log.error("!!!Could not format " + fileName + "!!!", e); } catch (BadLocationException e) { log.error("!!!Could not format " + fileName + "!!!", e); } catch (IOException e) { log.error("!!!Could not format " + fileName + "!!!", e); } catch (Exception e) { log.error("!!!Could not format " + fileName + "!!!", e); } finally { if (out != null) { out.close(); } } } }
From source file:com.sympedia.genfw.jdt.impl.JavaFormatterImpl.java
License:Open Source License
/** * @ADDED//from w ww. ja v a 2s . c om */ public static byte[] formatCode(byte[] source, CodeFormatter codeFormatter) { try { TextUtilities.class.getName(); } catch (Exception ex) { System.out.println("Omitted Java formatting because org.eclipse.jface.text is missing."); return source; } String contents = new String(source); IDocument doc = new Document(contents); TextEdit edit = codeFormatter.format(CodeFormatter.K_COMPILATION_UNIT, doc.get(), 0, doc.get().length(), 0, null); try { edit.apply(doc); contents = doc.get(); } catch (Exception exception) { JdtActivator.INSTANCE.log(exception); } return contents.getBytes(); }
From source file:com.thoratou.exact.processors.IndentUtil.java
License:Open Source License
public String javaCode(String input) { // take default Eclipse formatting options Map options = DefaultCodeFormatterConstants.getEclipseDefaultSettings(); options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_7); options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_7); options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_7); options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE); // change the option to wrap each enum constant on a new line options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ENUM_CONSTANTS, DefaultCodeFormatterConstants.createAlignmentValue(true, DefaultCodeFormatterConstants.WRAP_ONE_PER_LINE, DefaultCodeFormatterConstants.INDENT_ON_COLUMN)); // change the option to wrap each enum constant on a new line options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ASSIGNMENT, DefaultCodeFormatterConstants.createAlignmentValue(false, DefaultCodeFormatterConstants.WRAP_NO_SPLIT, DefaultCodeFormatterConstants.INDENT_ON_COLUMN)); // change the option to wrap each enum constant on a new line options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SELECTOR_IN_METHOD_INVOCATION, DefaultCodeFormatterConstants.createAlignmentValue(false, DefaultCodeFormatterConstants.WRAP_NO_SPLIT, DefaultCodeFormatterConstants.INDENT_ON_COLUMN)); CodeFormatter cf = ToolFactory.createCodeFormatter(options); IDocument dc = new Document(input); TextEdit te = cf.format(CodeFormatter.K_COMPILATION_UNIT, dc.get(), 0, dc.get().length(), 0, null); try {/* ww w . j av a2 s .com*/ te.apply(dc); } catch (MalformedTreeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } return dc.get(); }
From source file:com.worldline.awltech.i18ntools.wizard.core.modules.ResourceBundleWrapper.java
License:Open Source License
/** * Loads the currently selected compilation unit. *//*from w w w . j a va 2 s .c o m*/ private void loadCompilationUnit() { final IProject project = this.javaProject.getProject(); final IResource sourceFolderResource = project .getFolder(new Path(this.configuration.getJavaSourceFolder())); final IPackageFragmentRoot ipfr = this.javaProject.getPackageFragmentRoot(sourceFolderResource); IPackageFragment ipf = ipfr.getPackageFragment(this.packageName); if (!ipf.exists()) { try { ipf = ipfr.createPackageFragment(this.packageName, false, new NullProgressMonitor()); } catch (final JavaModelException e) { Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, RefactoringWizardMessages.ERROR_CREATE_PACKAGE.value(), e)); } } final String javaUnitName = this.resourceBundleName.concat(".java"); this.enumJavaCompilationUnit = ipf.getCompilationUnit(javaUnitName); if (!this.enumJavaCompilationUnit.exists()) { final String contents = this.createJavaUnitContents(); // Format the source code before trying to set it to the compilation unit. CodeFormatter formatter = ToolFactory.createCodeFormatter(this.javaProject.getOptions(true), ToolFactory.M_FORMAT_EXISTING); IDocument document = new Document(contents); TextEdit textEdit = formatter.format( CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS, contents, 0, contents.length(), 0, null); try { textEdit.apply(document); } catch (MalformedTreeException e1) { Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, RefactoringWizardMessages.ERROR_REFACTOR_TEMPLATE.value(), e1)); } catch (BadLocationException e1) { Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, RefactoringWizardMessages.ERROR_REFACTOR_TEMPLATE.value(), e1)); } try { // Set the source into the compilation unit. this.enumJavaCompilationUnit = ipf.createCompilationUnit(javaUnitName, document.get(), false, new NullProgressMonitor()); } catch (final JavaModelException e) { Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, RefactoringWizardMessages.ERROR_CREATE_CU.value(), e)); } } final ASTParser enumSourceParser = ASTParser.newParser(AST.JLS4); enumSourceParser.setProject(this.javaProject); enumSourceParser.setBindingsRecovery(true); enumSourceParser.setResolveBindings(true); enumSourceParser.setKind(ASTParser.K_COMPILATION_UNIT); enumSourceParser.setSource(this.enumJavaCompilationUnit); this.enumDomCompilationUnit = (CompilationUnit) enumSourceParser.createAST(new NullProgressMonitor()); this.enumDomCompilationUnit.recordModifications(); }