Blog-Archiv

Freitag, 14. Januar 2022

Highlighting Code as HTML by Internet API with Java

Highlighting source code as HTML is not so easy when you try to download some Java library and need to find out how to launch it on your code. But it's quite easy to copy & paste on the free website http://hilite.me. It supports a lot of programming languages, and it also offers a REST-API at http://hilite.me/api.

Here is a Java class that can call the API for you. It also shows how you can call a website by importing just JDK classes from java.net and java.io, not even using the new HttpClient. Mind that GET fails when the sent source code is too big, so I implemented a POST call, hilite.me accepts both. For a POST call, you must URL-encode the source code, and then write it together with all other parameters into the output-stream of HttpURLConnection, like done on line 49. You can see parameter names supported by hilite.me in the help text at the API location. The divstyles parameter doesn't work.

HiLiteJava.java
Highlights source code as HTML by calling http://hilite.me/api . Works only with valid Internet connection! Imports classes from java.net and java.io.
Field URL
private static final String URL = "http://hilite.me/api";
Field NEWLINE
private static final String NEWLINE = System.lineSeparator();
Field ENCODING
private static final String ENCODING = StandardCharsets.UTF_8.name();
Field parameters
private final String parameters;
Constructor activating line number generation.
public HiLiteJava() {
    this(true);
}
Constructor setting rendering style to "monokai".
public HiLiteJava(boolean lineNumbers) {
    this(lineNumbers, "monokai");
}
Constructor setting lexer to "java", see http://pygments.org/docs/styles/.
public HiLiteJava(boolean lineNumbers, String style) {
    this(lineNumbers, style, "java");
}
Constructor preparing all given parameters as URL parameters.
public HiLiteJava(boolean lineNumbers, String style, String lexer) {
    this.parameters = 
            "lexer="+lexer+"&"+
            "style="+style+"&"+
            (lineNumbers ? "linenos=1&" : "");
    // good styles are: "monokai", "borland", "emacs", "default", "manni", "trac" "vs"
}
Call the highlighting website with given source code and return the highlighted HTML representation. Mind that no line-formatting is done, so the given javaSourceCode should contain newlines and be indented correctly!
public String hilite(String javaSourceCode)    {
    try    {
        final URL url = new URL(URL);
        
        final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Accept-Charset", ENCODING);
        connection.setDoOutput(true); // triggers POST
        // big javaSourceCode works with POST only!
        try (final OutputStream output = connection.getOutputStream()) {
            String parameters = this.parameters+"code="+URLEncoder.encode(javaSourceCode, ENCODING);
            output.write(parameters.getBytes(ENCODING));
        }

        final int responseCode = connection.getResponseCode();
        if (responseCode != 200)
            throw new IllegalStateException("Response code was: "+responseCode);
        
        try (final BufferedReader inputReader = 
                    new BufferedReader(new InputStreamReader(connection.getInputStream(), ENCODING))) {
            final StringBuilder response = new StringBuilder();
            for (String line; (line = inputReader.readLine()) != null; ) {
                response.append(line);
                response.append(NEWLINE);
            }
            return response.toString();
        }
    }
    catch (Exception e)    {
        throw new RuntimeException(e);
    }
}
Test main(): try it out with a very short class!
public static void main(String[] args) throws Exception    {
    String javaSource = "class Foo\n{\n  void bar()\n  {\n  }\n}";
    System.out.println(new HiLiteJava().hilite(javaSource));
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
public class HiLiteJava
{
    private static final String URL = "http://hilite.me/api";
    private static final String NEWLINE = System.lineSeparator();
    private static final String ENCODING = StandardCharsets.UTF_8.name();
    
    private final String parameters;
    
    /** Constructor activating line number generation. */
    public HiLiteJava() {
        this(true);
    }
    
    /** Constructor setting rendering style to "monokai". */
    public HiLiteJava(boolean lineNumbers) {
        this(lineNumbers, "monokai");
    }
    
    /** Constructor setting lexer to "java", see http://pygments.org/docs/styles/. */
    public HiLiteJava(boolean lineNumbers, String style) {
        this(lineNumbers, style, "java");
    }
    
    /** Constructor preparing all given parameters as URL parameters. */
    public HiLiteJava(boolean lineNumbers, String style, String lexer) {
        this.parameters = 
                "lexer="+lexer+"&"+
                "style="+style+"&"+
                (lineNumbers ? "linenos=1&" : "");
        // good styles are: "monokai", "borland", "emacs", "default", "manni", "trac" "vs"
    }
    
    /**
     * Call the highlighting website with given source code and
     * return the highlighted HTML representation.
     * Mind that no line-formatting is done, so the given javaSourceCode
     * should contain newlines and be indented correctly!
     * @param javaSourceCode the text to highlight as HTML.
     * @return the highlighted HTML representing given source.
     */
    public String hilite(String javaSourceCode)    {
        try    {
            final URL url = new URL(URL);
            
            final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Accept-Charset", ENCODING);
            connection.setDoOutput(true); // triggers POST
            // big javaSourceCode works with POST only!
            try (final OutputStream output = connection.getOutputStream()) {
                String parameters = this.parameters+"code="+URLEncoder.encode(javaSourceCode, ENCODING);
                output.write(parameters.getBytes(ENCODING));
            }
    
            final int responseCode = connection.getResponseCode();
            if (responseCode != 200)
                throw new IllegalStateException("Response code was: "+responseCode);
            
            try (final BufferedReader inputReader = 
                        new BufferedReader(new InputStreamReader(connection.getInputStream(), ENCODING))) {
                final StringBuilder response = new StringBuilder();
                for (String line; (line = inputReader.readLine()) != null; ) {
                    response.append(line);
                    response.append(NEWLINE);
                }
                return response.toString();
            }
        }
        catch (Exception e)    {
            throw new RuntimeException(e);
        }
    }
    
    
    /** Test main(): try it out with a very short class! */
    public static void main(String[] args) throws Exception    {
        String javaSource = "class Foo\n{\n  void bar()\n  {\n  }\n}";
        System.out.println(new HiLiteJava().hilite(javaSource));
    }
}

All source code in this article has been highlighted by hilite.me. The style parameter I used was borland.

A big "Thank You" to the hilite.me website for supporting us freely! I hope it won't be closed ever. Also thanks for providing automation support, because I couldn't find any other site that offers such an API.




2 Kommentare:

rajanikanttabert hat gesagt…

Blue Titanium Cerakote (Cyante Carribean)
Blue Ti-te-Carribean is a titanium steel traditional titanium band ring aromatic carribean. titanium metal trim The cerakote is titanium industries a thin-walled type of cerakote, which titanium jewelry for piercings has been selectively bred for excellent $1,00.00 · ‎In stock

Unknown hat gesagt…

b545p6dynlv058 horse dildo,dog dildo,prostate massagers,horse dildo,wholesale sex toys,silicone sex doll,black dildos,sex chair,dildos z581y3hfmyp462