Format Files While Starting NetBeans IDE (Part 1)

Wouldn't you like to format a few files automatically, using the NetBeans built-in formatters, while NetBeans IDE starts up? Well, probably not. But in the case where you do want to do that, here's how:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import javax.swing.text.BadLocationException;
import org.netbeans.api.sendopts.CommandException;
import org.netbeans.editor.BaseDocument;
import org.netbeans.modules.editor.indent.api.Reformat;
import org.netbeans.spi.sendopts.Env;
import org.netbeans.spi.sendopts.Option;
import org.netbeans.spi.sendopts.OptionProcessor;
import org.openide.filesystems.FileUtil;
import org.openide.util.lookup.ServiceProvider;

@ServiceProvider(service = OptionProcessor.class)
public class FileFormattingCommandLineParser extends OptionProcessor {
    private static Option filesToBeFormatted =
            Option.requiredArgument(Option.NO_SHORT_NAME, "filesToBeFormatted");
    @Override
    protected Set<Option> getOptions() {
        return Collections.singleton(filesToBeFormatted);
    }
    @Override
    protected void process(Env env, Map<Option, String[]> value) throws CommandException {
        String[] args = (String[]) value.get(filesToBeFormatted);
        //Parse comma-separated list of command line values:
        String[] allFiles = args[0].split(",");
        for (final String stringOfFileToBeFormatted : allFiles) {
            File oneFileToBeFormatted = new File(stringOfFileToBeFormatted);
            Reader reader = null;
            try {
                //Get content of files:
                URL url = oneFileToBeFormatted.toURI().toURL();
                URLConnection conn = url.openConnection();
                reader = new InputStreamReader(conn.getInputStream());
                //Get mime type:
                String mime = FileUtil.toFileObject(oneFileToBeFormatted).getMIMEType();
                //Create a NetBeans BaseDocument,
                //constructed from the content above
                //and from the MIME type:
                final BaseDocument bd = new BaseDocument(false, mime);
                bd.read(reader, 0);
                //Reformat the BaseDocument:
                final Reformat rf = Reformat.get(bd);
                rf.lock();
                try {
                    bd.runAtomicAsUser(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                rf.reformat(0, bd.getLength());
                            } catch (BadLocationException ex) {
                            }
                        }
                    });
                } finally {
                    rf.unlock();
                }
                //Write the BaseDocument into the file:
                FileWriter fstream = new FileWriter(oneFileToBeFormatted);
                BufferedWriter out = new BufferedWriter(fstream);
                out.write(bd.getText(0, bd.getLength()));
                out.close();
            } catch (BadLocationException ex) {
            } catch (IOException ex) {
            }
        }
    }
}

What you have above is the definition of a new command line argument, "filesToBeFormatted", the values of which should be strings pointing to files, which will be formatted during the start up of NetBeans IDE:

netbeans --filesToBeFormatted "/home/geertjan/ABC/project.xml,/home/geertjan/ABC/bla.html"

Now see part 2!

Comments:

Using File.pathSeparator would be more conventional than a comma.

The URLConnection is probably unnecessary. Get the FileObject as you do now - but checking for null, in case the file does not exist! - then use FO.getInputStream to read its content. And do not use FileWriter to write it, since that will ignore details of its encoding and generally mangle things; use FileEncodingQuery to get an encoder on FO.getOutputStream.

Posted by Jesse Glick on August 15, 2011 at 01:51 AM PDT #

Post a Comment:
  • HTML Syntax: NOT allowed
About

Geertjan Wielenga (@geertjanw) is a Principal Product Manager in the Oracle Developer Tools group living & working in Amsterdam. He is a Java technology enthusiast, evangelist, trainer, speaker, and writer. He blogs here daily.

The focus of this blog is mostly on NetBeans (a development tool primarily for Java programmers), with an occasional reference to NetBeans, and sometimes diverging to topics relating to NetBeans. And then there are days when NetBeans is mentioned, just for a change.

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
12
13
14
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today