1
2
3
4
5
6
7
8
9
10
11 package de.funfried.netbeans.plugins.external.formatter;
12
13 import java.util.List;
14 import java.util.Objects;
15 import java.util.regex.Pattern;
16
17 import javax.swing.text.Document;
18
19 import org.apache.commons.lang3.StringUtils;
20 import org.netbeans.api.java.lexer.JavaTokenId;
21 import org.netbeans.modules.editor.NbEditorUtilities;
22 import org.openide.util.NbBundle;
23
24
25
26
27
28
29 @NbBundle.Messages({
30 "CSS=CSS",
31 "HTML=HTML",
32 "JAVA=Java",
33 "JAVASCRIPT=JavaScript",
34 "JSON=Json",
35 "XML=XML",
36 "SQL=SQL"
37 })
38 public enum MimeType {
39 CSS("text/css"), HTML("application/xhtml+xml", "text/html", "text/xhtml"), JAVA(JavaTokenId.language().mimeType()), JAVASCRIPT("text/javascript"), JSON("text/x-json",
40 "^text/(.*)\\+x-json$"), XML("text/xml", "^text/(.*)\\+xml$"), SQL("application/sql", "text/sql", "text/x-sql", "text/plain");
41
42 private final String[] mimeTypes;
43
44 MimeType(String... mimeTypes) {
45 this.mimeTypes = mimeTypes;
46 }
47
48 public String getDisplayName() {
49 return NbBundle.getMessage(MimeType.class, this.toString());
50 }
51
52 public boolean canHandle(String mimeType) {
53 if (StringUtils.isBlank(mimeType)) {
54 return false;
55 }
56
57 for (String type : mimeTypes) {
58 if (type.startsWith("^") && Pattern.matches(type, mimeType)) {
59 return true;
60 } else if (Objects.equals(type, mimeType)) {
61 return true;
62 }
63 }
64
65 return false;
66 }
67
68 public static boolean canHandle(List<MimeType> types, String mimeType) {
69 if (StringUtils.isBlank(mimeType)) {
70 return false;
71 }
72
73 for (MimeType t : types) {
74 for (String type : t.mimeTypes) {
75 if (type.startsWith("^") && Pattern.matches(type, mimeType)) {
76 return true;
77 } else if (Objects.equals(type, mimeType)) {
78 return true;
79 }
80 }
81 }
82
83 return false;
84 }
85
86 public static MimeType getByMimeType(String mimeType) {
87 for (MimeType mime : MimeType.values()) {
88 if (mime.canHandle(mimeType)) {
89 return mime;
90 }
91 }
92
93 return null;
94 }
95
96 public static MimeType getMimeType(Document document) {
97 return getByMimeType(getMimeTypeAsString(document));
98 }
99
100 public static String getMimeTypeAsString(Document document) {
101 if (document != null) {
102 return NbEditorUtilities.getMimeType(document);
103 }
104
105 return null;
106 }
107 }