Example usage for org.eclipse.jdt.core.formatter CodeFormatter K_UNKNOWN

List of usage examples for org.eclipse.jdt.core.formatter CodeFormatter K_UNKNOWN

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.formatter CodeFormatter K_UNKNOWN.

Prototype

int K_UNKNOWN

To view the source code for org.eclipse.jdt.core.formatter CodeFormatter K_UNKNOWN.

Click Source Link

Document

Unknown kind

Since 3.6, if the corresponding comment options are set to true then it is also possible to format the comments on the fly by adding the #F_INCLUDE_COMMENTS flag to this kind of format.

Usage

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();/*from  ww  w  .  ja  va2 s . co  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 {/*from ww  w  .j av  a 2 s .  c  om*/
        //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.bsiag.eclipse.jdt.java.formatter.CommentsPreparator.java

License:Open Source License

private void formatCode(int javadocNoFormatCloseStart, int javadocNoFormatCloseEnd) {
    int openingTagLastIndex = tokenEndingAt(this.formatCodeTagOpenEnd);
    int closingTagFirstIndex = tokenStartingAt(javadocNoFormatCloseStart);

    int codeStartPosition = this.formatCodeTagOpenEnd + 1;
    int codeEndPosition = javadocNoFormatCloseStart - 1;
    StringBuilder codeBuilder = new StringBuilder(codeEndPosition - codeStartPosition + 1);
    int[] positionMapping = new int[codeEndPosition - codeStartPosition + 1];
    // ^ index: original source position (minus startPosition), value: position in code string
    getCodeToFormat(codeStartPosition, codeEndPosition, codeBuilder, positionMapping);

    List<Token> formattedTokens = getCommentCodeFormatter().prepareFormattedCode(codeBuilder.toString(),
            CodeFormatter.K_UNKNOWN);

    if (formattedTokens == null) {
        disableFormattingExclusively(openingTagLastIndex, closingTagFirstIndex);
        closingTagFirstIndex = tokenStartingAt(javadocNoFormatCloseStart);
        cleanupHTMLElement(openingTagLastIndex, closingTagFirstIndex, false);
        return;/*from   w  w  w . j  a va  2 s . co m*/
    }

    formattedTokens = translateFormattedTokens(codeStartPosition, formattedTokens, positionMapping, null);
    // there are too few linebreaks at the start and end
    Token start = formattedTokens.get(0);
    start.putLineBreaksBefore(start.getLineBreaksBefore() + 1);
    Token end = formattedTokens.get(formattedTokens.size() - 1);
    end.putLineBreaksAfter(end.getLineBreaksAfter() + 1);
    // and there may be too many line breaks before closing tag
    this.ctm.get(closingTagFirstIndex).clearLineBreaksBefore();

    List<Token> tokensToReplace = this.commentStructure.subList(openingTagLastIndex + 1, closingTagFirstIndex);
    tokensToReplace.clear();
    tokensToReplace.addAll(formattedTokens);
    cleanupHTMLElement(openingTagLastIndex, openingTagLastIndex + formattedTokens.size() + 1, true);
    noSubstituteWrapping(codeStartPosition, codeEndPosition);
}

From source file:com.bsiag.eclipse.jdt.java.formatter.DefaultCodeFormatter.java

License:Open Source License

List<Token> prepareFormattedCode(String source, int kind) {
    if (!init(source))
        return null;

    this.astRoot = parseSourceCode(kind);
    if (this.astRoot == null)
        return null;

    if (kind != CodeFormatter.K_UNKNOWN)
        findHeader();/*from w w  w  .j ava  2 s. c om*/

    prepareSpaces();
    prepareLineBreaks();
    prepareComments();
    prepareWraps(kind);

    this.tokenManager.applyFormatOff();

    return this.tokens;
}

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 {//w  w w.  j a  va  2s .  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:de.tub.tfs.henshin.tgg.interpreter.gui.TranslationJob.java

License:Open Source License

protected IStatus run(IProgressMonitor monitor) {
    if (inputFile == null)
        return Status.OK_STATUS;
    if (this.getThread() != null) {
        this.getThread().setName("TranslationJob " + this.getThread().getName());
    }/*w w w  .j av a 2s. c  o m*/
    synchronized (lock) {
        // check that grammar is loaded
        if (LoadHandler.trSystems.size() == 0) {
            return new Status(RUNNING, "tgg-plugin", "Transformation System was not loaded");
        }

        // clear list of rules from previous executions
        //TggUtil.initClassConversions();
        ExecutionTimes executionTimes = new ExecutionTimes();
        try {
            monitor.beginTask("Translating " + inputURI.lastSegment(), 3);
            System.out.println("=====");
            System.out.println("Translating: " + inputURI.lastSegment());
            long time0 = System.currentTimeMillis();
            monitor.subTask("Loading input");
            ResourceSet resSet = new ResourceSetImpl();
            HashMap<String, Object> options = new HashMap<String, Object>();
            options.put(XMLResource.OPTION_EXTENDED_META_DATA, Boolean.TRUE);
            options.put(XMLResource.OPTION_EXTENDED_META_DATA, Boolean.TRUE);
            options.put(XMLResource.OPTION_SCHEMA_LOCATION, Boolean.TRUE);
            options.put(XMLResource.OPTION_USE_ENCODED_ATTRIBUTE_STYLE, Boolean.TRUE);
            options.put(XMLResource.OPTION_USE_ENCODED_ATTRIBUTE_STYLE, Boolean.TRUE);
            options.put(XMLResource.OPTION_USE_LEXICAL_HANDLER, Boolean.TRUE);

            resSet.getLoadOptions().putAll(options);
            Resource res = resSet.getResource(inputURI, true);

            // Print out syntax parsing errors 
            // and abort translation if errors occur
            EList<Diagnostic> errors = res.getErrors();
            if (!errors.isEmpty()) {
                String msg = "===========================\n";
                msg += "Translation failed. No output was generated. The following syntax errors occured while parsing:\n";
                for (Diagnostic d : errors) {
                    msg += "(" + inputURI.lastSegment() + ") line " + d.getLine() + ": " + d.getMessage()
                            + "\n";
                    msg += "-------------------------------\n";
                }
                msg += "===========================\n";
                throw new RuntimeException(msg);
            }

            EObject inputRoot = (EObject) res.getContents().get(0);
            inputEObjects = res.getContents(); // add all of root
            tggTransformation = new TggTransformationImpl();
            tggTransformation.setStartTime(Long.parseLong(engineOptions.get("_StartTime")));
            tggTransformation.setInput(inputEObjects);
            tggTransformation.opRulesList.clear();

            // Validate input AST based on custom constraints 
            org.eclipse.emf.common.util.Diagnostic validation_result = Diagnostician.INSTANCE
                    .validate(inputRoot);
            if (!validation_result.getChildren().isEmpty()) {
                String msg = "===========================\n";
                msg += "Translation failed. No output was generated. The following syntax errors occured while parsing:\n";
                for (org.eclipse.emf.common.util.Diagnostic d : validation_result.getChildren()) {
                    msg += "(" + inputURI.lastSegment() + ") " + d.getMessage() + " (" + d.getSource() + ")\n";
                    msg += "-------------------------------\n";
                }
                msg += "===========================\n";
                throw new RuntimeException(msg);
            }

            emfEngine = tggTransformation.getEmfEngine();
            JavaScriptTggInitializer.registerWithScriptingEngine(emfEngine.getScriptEngine());
            emfEngine.getScriptEngine().put("emfEngine", emfEngine);
            Bindings bindings = emfEngine.getScriptEngine().getBindings(ScriptContext.ENGINE_SCOPE);
            synchronized (this.engineOptions) {
                String init = this.engineOptions.get("Initialisation");
                if (init == null) {
                    for (Entry<String, String> entry : this.engineOptions.entrySet()) {

                        bindings.put(entry.getKey(), entry.getValue());
                    }
                } else {
                    for (Entry<String, String> entry : this.engineOptions.entrySet()) {
                        bindings.put(entry.getKey(), entry.getValue());
                    }

                    init = this.engineOptions.get("Initialisation");
                    if (init != null) {
                        if (init.startsWith("{*")) {
                            init = init.substring(2, init.length() - 2);
                        }
                        try {
                            //org.eclipse.core.runtime.Platform

                            emfEngine.getScriptEngine().eval(init);
                        } catch (Throwable e) {
                            System.err.println("Error while initialising Grammar!");
                            e.printStackTrace();
                        }

                        this.engineOptions.remove("Initialisation");
                    }
                }
            }

            this.emfEngine.updateOptions();

            long time1 = System.currentTimeMillis();
            long stage1 = time1 - time0;
            System.out.println("Stage 1 -- Loading: " + stage1 + " ms");
            monitor.worked(1);
            if (monitor.isCanceled()) {
                monitor.done();
                return Status.CANCEL_STATUS;
            }

            Iterator<TGG> moduleIt = LoadHandler.trSystems.iterator();
            List<String> fileNames = LoadHandler.trFileNames;

            boolean foundApplicationForRound = false;
            boolean foundApplicationForModule = false;

            boolean newMatchesArePossible = true;
            boolean initialRound = true;
            // execute all modules as long as there are matches
            TGG module = null;
            ArrayList<Module> modules = new ArrayList<Module>();
            ArrayList<List<Rule>> opRules = new ArrayList<List<Rule>>();

            // retrieve modules and lists of operational rules
            while (moduleIt.hasNext()) {
                module = moduleIt.next();
                modules.add(module);
                opRules.add(getOpRules(module));
                //for (Module module2 : priorModules) {
                //   opRules.add(getOpRules(module2));
                //}
                //priorModules.add(module);
            }

            while (newMatchesArePossible) {
                foundApplicationForRound = false;
                // execute all modules once
                for (int modulePos = 0; modulePos < modules.size(); modulePos++) {
                    tggTransformation.setOpRuleList(opRules.get(modulePos));
                    tggTransformation.setNullValueMatching(modules.get(modulePos).isNullValueMatching());

                    String trFileName = fileNames.get(modulePos);
                    monitor.subTask("Applying " + trFileName);
                    if (debug)
                        System.out.println("Applying " + trFileName);

                    foundApplicationForModule = tggTransformation.applyRules(monitor, "Applying " + trFileName,
                            debug);
                    monitor.worked(1);
                    if (monitor.isCanceled()) {
                        monitor.done();
                        return Status.CANCEL_STATUS;
                    }
                    foundApplicationForRound = foundApplicationForRound || foundApplicationForModule;

                    for (int i = 0; i < modulePos; i++) {

                        tggTransformation.setOpRuleList(opRules.get(i));
                        tggTransformation.setNullValueMatching(modules.get(i).isNullValueMatching());

                        trFileName = fileNames.get(i);
                        monitor.subTask("Applying " + trFileName);
                        if (debug)
                            System.out.println("Applying " + trFileName);

                        foundApplicationForModule = tggTransformation.applyRules(monitor,
                                "Applying " + trFileName, debug);
                        monitor.worked(1);
                        if (monitor.isCanceled()) {
                            monitor.done();
                            return Status.CANCEL_STATUS;
                        }
                        foundApplicationForRound = foundApplicationForRound || foundApplicationForModule;
                    }
                }

                if (!initialRound && foundApplicationForRound)
                    System.out.println(
                            "Warning: some ruleapplications depend on rules that are applied in a subsequent module. This can cause inefficient executions. "
                                    + "Try to reorder the modules or rules.");

                initialRound = false;
                newMatchesArePossible = foundApplicationForRound;
            }

            //            while (moduleIt.hasNext() && fileNames.hasNext()) {
            //               module = moduleIt.next();
            //               trFileName = fileNames.next();
            //               addFTRules(module);
            //               tggTransformation.setNullValueMatching(module.isNullValueMatching());
            //
            //               monitor.subTask("Applying " + trFileName);
            //
            //               tggTransformation.applyRules(monitor,"Applying " + trFileName,debug);
            //               monitor.worked(1);
            //               if (monitor.isCanceled()) {
            //                  monitor.done();
            //                  return Status.CANCEL_STATUS;
            //               }
            //            }
            if (monitor.isCanceled()) {
                monitor.done();
                return Status.CANCEL_STATUS;
            }
            long time2 = System.currentTimeMillis();
            long stage2 = time2 - time1;
            System.out.println("Stage 2 -- Transformation: " + stage2 + " ms");
            monitor.subTask("Saving result");
            List<EObject> roots = tggTransformation.getGraph().getRoots();

            Iterator<EObject> it = roots.iterator();
            EObject targetRoot = null;
            EObject current = null;
            //TGG tgg = LoadHandler.layoutModels.get(0);
            boolean targetRootFound = false;
            Class<?> targetClass = null;
            if (this.engineOptions.containsKey("TargetClass")) {
                try {
                    String targetClassScript = this.engineOptions.get("TargetClass");
                    if (targetClassScript.startsWith("{*")) {
                        targetClassScript = targetClassScript.substring(2, targetClassScript.length() - 2);
                    }
                    targetClass = (Class) emfEngine.getScriptEngine().eval(targetClassScript);

                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
            while (it.hasNext() && !targetRootFound) {
                current = it.next();
                if (NodeUtil.isTargetClass(module, current.eClass())) {
                    targetRoot = current;
                    targetRootFound = true;

                    if (targetClass != null && !targetClass.isInstance(targetRoot)) {
                        targetRoot = null;
                        targetRootFound = false;
                    }

                }
            }

            String moduleName = module.getName();
            String[] moduleNameComponents = moduleName.split("2");
            if (moduleNameComponents.length == 2)
                targetExt = moduleNameComponents[1];

            if (targetExt != null && targetExt.isEmpty()) {
                targetExt = DEFAULT_EXT;
            }
            if (this.engineOptions.containsKey("TargetExtension")) {
                targetExt = this.engineOptions.get("TargetExtension");
            }
            if (targetRoot != null) {
                PriorityQueue<AbstractPostProcessorFactory> postProcessorFactories = getPostProcessorFactories();
                PriorityQueue<AbstractPostProcessorFactory> postProcessorFactories2 = new PriorityQueue<AbstractPostProcessorFactory>(
                        postProcessorFactories);
                EObject newRoot = targetRoot;
                while (!postProcessorFactories2.isEmpty()) {
                    AbstractPostProcessorFactory postProcessorFactory = postProcessorFactories2.poll();
                    if (postProcessorFactory.isValid(inputURI)) {
                        AbstractPostProcessor postProcessor = postProcessorFactory.createPostProcessor(newRoot);

                        postProcessor.registerSharedObjects(sharedObjectRegistry);

                        newRoot = postProcessor.process();

                    }
                }

                targetRoot = newRoot;
                // remove all backreferences
                TreeIterator<EObject> nodesIt = targetRoot.eAllContents();
                EObject targetObject = targetRoot;
                //AbstractTarget tNode;

                removeT2C(targetObject);

                while (nodesIt.hasNext()) {
                    targetObject = nodesIt.next();
                    removeT2C(targetObject);
                }
                if (targetExt == null) {
                    Export.saveModel(resSet, roots, xmiURI);
                } else {
                    this.outputURI = this.inputURI.trimFileExtension().appendFileExtension(targetExt);
                    Export.saveTargetModel(resSet, targetRoot, outputURI, postProcessorFactories, inputURI,
                            sharedObjectRegistry);
                }
            } else {
                System.out.println("No target root!");
            }
            monitor.worked(1);
            if (useOutputFolder) {
                this.outputURI = outputURI.trimSegments(1).appendSegment("output")
                        .appendSegment(outputURI.lastSegment());
            }
            Import.unloadModel(resSet, outputURI);
            resSet.getResource(inputURI, true).unload();

            try {
                if (outputURI.isPlatformResource()) {
                    String platformString = outputURI.toPlatformString(true);
                    IFile file = (IFile) ResourcesPlugin.getWorkspace().getRoot().findMember(platformString);
                    Path path = Paths.get(file.getLocation().toString());
                    Charset charset = StandardCharsets.UTF_8;
                    String content = new String(Files.readAllBytes(path), charset);
                    CodeFormatter cf = new DefaultCodeFormatter();
                    TextEdit te = cf.format(CodeFormatter.K_UNKNOWN, content, 0, content.length(), 0, null);
                    IDocument dc = new Document(content);
                    te.apply(dc);
                    Files.write(path, dc.get().getBytes(charset));
                }
            } catch (Exception e) {
                //e.printStackTrace();
            }
            long time3 = System.currentTimeMillis();
            long stage3 = time3 - time2;
            System.out.println("Stage 3 -- Saving: " + stage3 + " ms");
            executionTimes.stage1 = stage1;
            executionTimes.stage2 = stage2;
            executionTimes.stage3 = stage3;
            executionTimes.overall = stage1 + stage2 + stage3;
        } finally {
            monitor.done();
        }
        // put the execution time for this file in the global list
        synchronized (executionTimesMap) {
            executionTimesMap.put(inputURI.path(), executionTimes);
        }
        for (Module m : LoadHandler.trSystems) {
            cleanGrammar(m);
        }

        if (emfEngine != null)
            emfEngine.clearCache();

        if (this.getThread() != null && this.getThread().getName().startsWith("TranslationJob ")) {
            this.getThread().setName(this.getThread().getName().replaceFirst("TranslationJob ", ""));
        }
        if (!monitor.isCanceled()) {
            // Start next Translation Job
            new TranslationJobCreator() {

                @Override
                public Job createJob() {
                    TranslationJob job = new TranslationJob(inputFiles, useOutputFolder, engineOptions, lock);
                    job.setTimesMap(executionTimesMap);
                    job.setPriority(Job.DECORATE);

                    return job;
                }
            }.createJob().schedule();
        }
        return Status.OK_STATUS;
    }
}

From source file:edu.brown.cs.bubbles.bedrock.BedrockEditor.java

License:Open Source License

/********************************************************************************/

void formatCode(String proj, String bid, String file, int spos, int epos, IvyXmlWriter xw)
        throws BedrockException {
    FileData fd = findFile(proj, file, bid, null);

    if (fd == null)
        throw new BedrockException("Compilation unit for file " + file + " not available for formatting");

    ICompilationUnit icu = fd.getEditableUnit(bid);
    String cnts = null;//from  w w  w  .  j a va  2 s.  c  om
    try {
        cnts = icu.getBuffer().getContents();
    } catch (JavaModelException e) {
        throw new BedrockException("Unable to get compilation unit contents: " + e, e);
    }

    IRegion[] irgns = new IRegion[1];
    if (spos < 0)
        spos = 0;
    if (epos <= 0)
        epos = cnts.length();
    if (epos <= spos)
        throw new BedrockException("Bad region to format");
    irgns[0] = new Region(spos, epos - spos);

    if (code_formatter == null) {
        code_formatter = ToolFactory.createCodeFormatter(null);
    }

    // TODO: why doesn't K_CLASS_BODY_DECLARATIONS work here?
    // TextEdit te = code_formatter.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS,cnts,irgns,0,null);
    TextEdit te = code_formatter.format(CodeFormatter.K_UNKNOWN, cnts, irgns, 0, null);

    if (te == null)
        throw new BedrockException("Unable to format method");

    BedrockUtil.outputTextEdit(te, xw);
}

From source file:edu.brown.cs.bubbles.rebase.newjava.RebaseJcompSemantics.java

License:Open Source License

/********************************************************************************/

@Override//from   w w w  . ja  va  2 s .  c  o  m
public void formatCode(String cnts, int spos, int epos, IvyXmlWriter xw) {
    CodeFormatter cf = ToolFactory.createCodeFormatter(null);

    if (spos < 0)
        spos = 0;
    if (epos <= 0)
        epos = cnts.length();
    if (epos <= spos)
        return;

    TextEdit te = cf.format(CodeFormatter.K_UNKNOWN, cnts, spos, epos - spos, 0, null);

    if (te == null)
        return;

    RebaseUtil.outputTextEdit(te, xw);
}

From source file:mx.itesm.mexadl.util.Util.java

License:Open Source License

/**
 * Format the contents of a Java file using Eclipse's built-in code
 * formatter.//from w ww.j  a va  2  s .c  o  m
 * 
 * @param outputFile
 * @param contentFile
 * @throws IOException
 * @throws MalformedTreeException
 * @throws BadLocationException
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void formatFileContent(final File outputFile, final File contentFile)
        throws IOException, MalformedTreeException, BadLocationException {
    Map options;
    String source;
    TextEdit edit;
    Writer writer;
    int contentKind;
    IDocument document;
    CodeFormatter codeFormatter;

    // use Eclipse's default formatting options
    writer = new BufferedWriter(new FileWriter(outputFile));
    options = DefaultCodeFormatterConstants.getEclipseDefaultSettings();

    // Compiler settings to be able to format 1.6 code
    options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_6);
    options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_6);
    options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_6);

    // Instantiate the default code formatter with the given options
    codeFormatter = ToolFactory.createCodeFormatter(options);
    source = Util.getFileContents(contentFile);
    document = new org.eclipse.jface.text.Document(source);

    // Decide code kind and try to apply format
    contentKind = CodeFormatter.K_UNKNOWN;
    if (outputFile.toString().endsWith(Util.JAVA_EXTENSION)) {
        contentKind = CodeFormatter.K_COMPILATION_UNIT;
    }
    edit = codeFormatter.format(contentKind, source, 0, source.length(), 0,
            System.getProperty("line.separator"));
    if (edit != null) {
        edit.apply(document);
    }

    // Save to output file
    writer.write(document.get());
    writer.close();
}

From source file:net.sf.commonclipse.Generator.java

License:Apache License

/**
 * Generates the method by://from ww  w .j  a  v a 2 s  . c  om
 * <ul>
 * <li>call createMethod</li>
 * <li>format the given method</li>
 * <li>add it to type</li>
 * <li>call addImports</li>
 * </ul>.
 * @param type IType
 * @param cu compilation unit
 * @param shell Shell for messages
 * @param monitor progress monitor, updated during processing
 * @throws JavaModelException any exception in method generation
 */
public void generateMethod(IType type, ICompilationUnit cu, Shell shell, IProgressMonitor monitor)
        throws JavaModelException {
    String className = type.getElementName();

    String title = MessageFormat.format(CCMessages.getString("Generator.generating"), //$NON-NLS-1$
            new Object[] { className });
    monitor.beginTask(title, 100);
    monitor.worked(10);

    monitor.setTaskName(title + CCMessages.getString("Generator.parsing")); //$NON-NLS-1$
    String src = createMethod(type);
    monitor.worked(30);

    monitor.setTaskName(title + CCMessages.getString("Generator.formatting")); //$NON-NLS-1$
    Document document = new Document(src);

    TextEdit text = ToolFactory.createCodeFormatter(null).format(CodeFormatter.K_UNKNOWN, src, 0, src.length(),
            getIndentUsed(type, cu) + 1, null);

    try {
        text.apply(document);
    } catch (MalformedTreeException ex) {
        MessageDialog.openError(shell, CCMessages.getString("Generator.errortitle"), ex.getMessage()); //$NON-NLS-1$
    } catch (BadLocationException ex) {
        MessageDialog.openError(shell, CCMessages.getString("Generator.errortitle"), ex.getMessage()); //$NON-NLS-1$
    }

    monitor.worked(20);

    monitor.setTaskName(title + CCMessages.getString("Generator.adding")); //$NON-NLS-1$
    type.createMethod(document.get() + LINE_SEPARATOR, null, false, null);

    monitor.worked(20);

    monitor.setTaskName(title + CCMessages.getString("Generator.imports")); //$NON-NLS-1$
    addImports(type);
    monitor.worked(20);

    monitor.done();
}