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