Skip to content

Instantly share code, notes, and snippets.

@florentdupont
Created October 10, 2013 17:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save florentdupont/6922129 to your computer and use it in GitHub Desktop.
Save florentdupont/6922129 to your computer and use it in GitHub Desktop.
Code source de l'article "Formater du code Java avec JDT"
package flo;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.formatter.CodeFormatter;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.text.edits.MalformedTreeException;
import org.eclipse.text.edits.TextEdit;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class JavaFormat {
public static void main(String[] args) throws MalformedTreeException, BadLocationException {
String code = "import java.util.Date; public class geo{public static void main(String[] args){System.out.println(\"geo\");}}";
String formatterFile = "D:\\projets\\quality\\eclipse\\foundation-formatter.xml";
URL prefsFile = JavaFormat.class.getClassLoader().getResource("org.eclipse.jdt.core.prefs");
// depuis fichier de formatter XML
System.out.println(format(code, formatterFile));
// depuis fichier de préférences
System.out.println(format(code, prefsFile.getPath()));
}
public static String format(String source, String formatter) throws MalformedTreeException, BadLocationException {
File formatterFile = new File(formatter);
Map<String, String> options = null;
if("org.eclipse.jdt.core.prefs".equals(formatterFile.getName())) {
options = readPreferences(formatter);
}
else if(formatterFile.getName().endsWith("xml")) {
options = readFormatter(formatter);
}
// pour tous les autres cas, options reste null et dans ce cas, un formatteur par défaut est appliqué.
return formatFromOptions(source, options);
}
public static String formatFromOptions(String source, Map<String, String> options) {
CodeFormatter formatter = ToolFactory.createCodeFormatter(options);
TextEdit textEdit = formatter.format(CodeFormatter.K_COMPILATION_UNIT, source, 0, source.length(), 0, null);
IDocument document = new Document(source);
try {
textEdit.apply(document);
} catch (MalformedTreeException e) {
e.printStackTrace();
} catch (BadLocationException e) {
e.printStackTrace();
}
return document.get();
}
/**
* Parse le formatter au format XML pour alimenter les options.
*
* @param filePath
* @return
*/
private static Map<String, String> readFormatter(String filename) {
Map<String, String> options = new TreeMap<String, String>();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try {
DocumentBuilder builder = factory.newDocumentBuilder();
org.w3c.dom.Document doc = builder.parse(filename);
// Create a XPathFactory
XPathFactory xFactory = XPathFactory.newInstance();
// Create a XPath object
XPath xpath = xFactory.newXPath();
// Compile the XPath expression
XPathExpression expr = xpath.compile("//setting");
// Run the query and get a nodeset
Object result = expr.evaluate(doc, XPathConstants.NODESET);
// Cast the result to a DOM NodeList
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
Node id = nodes.item(i).getAttributes().getNamedItem("id");
Node value = nodes.item(i).getAttributes().getNamedItem("value");
options.put(id.getNodeValue(), value.getNodeValue());
}
} catch (Exception e) {
e.printStackTrace();
}
return options;
}
/** lit le fichier de configuration org.eclipse.jdt.core.prefs
*
* ce fichier est présent dans le workspace .metadata\.plugins\org.eclipse.core.runtime\.settings
* */
private static Map<String, String> readPreferences(String filename) {
BufferedInputStream stream = null;
File configFile = new File(filename);
try {
stream = new BufferedInputStream(new FileInputStream(configFile));
final Properties formatterOptions = new Properties();
formatterOptions.load(stream);
// un Properties implémente Map<Object, Object> => On peut donc récupérer nos propriétés sous forme de Map de cette manière.
return (Map)formatterOptions;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
/* ignore */
}
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment