fr.quatrevieux.araknemu.util.Escape.html(String)   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
dl 0
loc 2
ccs 1
cts 1
cp 1
crap 1
rs 10
eloc 2
1
/*
2
 * This file is part of Araknemu.
3
 *
4
 * Araknemu is free software: you can redistribute it and/or modify
5
 * it under the terms of the GNU Lesser General Public License as published by
6
 * the Free Software Foundation, either version 3 of the License, or
7
 * (at your option) any later version.
8
 *
9
 * Araknemu is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 * GNU Lesser General Public License for more details.
13
 *
14
 * You should have received a copy of the GNU Lesser General Public License
15
 * along with Araknemu.  If not, see <https://www.gnu.org/licenses/>.
16
 *
17
 * Copyright (c) 2017-2020 Vincent Quatrevieux
18
 */
19
20
package fr.quatrevieux.araknemu.util;
21
22
import org.apache.commons.lang3.StringUtils;
23
24
import java.io.UnsupportedEncodingException;
25
import java.net.URLEncoder;
26
import java.nio.charset.StandardCharsets;
27
28
/**
29
 * Utility class for escape string
30
 */
31
public final class Escape {
32
    // Replacement pairs
33
    // The two firsts pairs are used to ignore substrings :
34
    // the client already escape < and > when sending message, so ignore &lt; and &gt; to ensure that sending ">" will not be displayed as "&gt;"
35 1
    private static final String[] TO_ESCAPE = new String[] {"&lt;", "&gt;", "<", ">", "&", "|"};
36 1
    private static final String[] REPLACEMENT = new String[] {"&lt;", "&gt;", "&lt;", "&gt;", "&amp;", ""};
37
38
    private Escape() {}
39
40
    /**
41
     * Escape HTML chars
42
     * Note: "&lt;" and "&gt;" sequences are ignored due to client side encoding
43
     *
44
     * @param value Value to escape
45
     *
46
     * @return Escaped (safe) value
47
     */
48
    public static String html(String value) {
49 1
        return StringUtils.replaceEach(value, TO_ESCAPE, REPLACEMENT);
50
    }
51
52
    /**
53
     * Perform URL encode
54
     *
55
     * @param value Value to encode
56
     *
57
     * @return Encoded value
58
     */
59
    public static String url(String value) {
60
        try {
61 1
            return URLEncoder.encode(value, StandardCharsets.UTF_8.name());
62
        } catch (UnsupportedEncodingException e) {
63
            throw new RuntimeException(e);
0 ignored issues
show
Best Practice introduced by
Dedicated exceptions should be preferred over throwing the generic Exception.
Loading history...
64
        }
65
    }
66
}
67