]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.debug.browser/src/org/simantics/debug/browser/utils/Escapes.java
Migrated source code from Simantics SVN
[simantics/platform.git] / bundles / org.simantics.debug.browser / src / org / simantics / debug / browser / utils / Escapes.java
1 /*******************************************************************************\r
2  * Copyright (c) 2016 Association for Decentralized Information Management\r
3  * in Industry THTH ry.\r
4  * All rights reserved. This program and the accompanying materials\r
5  * are made available under the terms of the Eclipse Public License v1.0\r
6  * which accompanies this distribution, and is available at\r
7  * http://www.eclipse.org/legal/epl-v10.html\r
8  *\r
9  * Contributors:\r
10  *     THTH ry - initial API and implementation\r
11  *******************************************************************************/\r
12 package org.simantics.debug.browser.utils;\r
13 \r
14 public class Escapes {\r
15 \r
16     public static String html(String s) {\r
17         if (!containsAnyOf(s, HTML_CHARS_TO_ESCAPE))\r
18             return s;\r
19         return batchReplace(s, HTML_CHARS_TO_ESCAPE, HTML_CHAR_REPLACEMENTS);\r
20     }\r
21 \r
22     private static final char[] HTML_CHARS_TO_ESCAPE = { '&', '<', '>', '\n' };\r
23     private static final String[] HTML_CHAR_REPLACEMENTS = { "&amp;", "&lt;", "&gt;", "<br/>" };\r
24 \r
25     private static boolean containsAnyOf(String s, char[] chars) {\r
26         int l = s.length();\r
27         for (int i = 0; i < l; ++i) {\r
28             char p = s.charAt(i);\r
29             for (char ch : chars)\r
30                 if (p == ch)\r
31                     return true;\r
32         }\r
33         return false;\r
34     }\r
35 \r
36     private static String batchReplace(String s, char[] charsToReplace, String[] replacements) {\r
37         int l = s.length();\r
38         int rl = charsToReplace.length;\r
39         StringBuilder sb = new StringBuilder(l*2);\r
40         nextChar:\r
41             for (int i = 0; i < l; ++i) {\r
42                 char p = s.charAt(i);\r
43                 for (int j = 0; j < rl; ++j) {\r
44                     if (p == charsToReplace[j]) {\r
45                         sb.append(replacements[j]);\r
46                         continue nextChar;\r
47                     }\r
48                 }\r
49                 sb.append(p);\r
50             }\r
51         return sb.toString();\r
52     }\r
53 \r
54     public static void main(String[] args) {\r
55         System.out.println(html("><&\nfoobar\n<>"));\r
56     }\r
57 \r
58 }\r