001/*
002 *  Copyright 2019 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.plugins.core.ui.script;
017
018import org.apache.commons.lang3.StringUtils;
019
020import com.google.gson.Gson;
021import com.google.gson.GsonBuilder;
022
023final class ScriptResultFormatter
024{
025    private static final String[][] __STACKTRACE_REPLACEMENTS = {
026            {"\r\n", "<br>"},
027            {"\n\r", "<br>"},
028            {"\r", "<br>"},
029            {"\n", "<br>"},
030    };
031    
032    private static final Gson __GSON = new GsonBuilder()
033            .setPrettyPrinting()
034            .disableHtmlEscaping()
035            .create();
036    
037    private ScriptResultFormatter()
038    { }
039    
040    static String htmlFormatResult(Object result)
041    {
042        if (result instanceof String)
043        {
044            // can be HTML => do not wrap around "<pre>" tag ! keep as it is
045            return (String) result;
046        }
047        
048        String value;
049        try
050        {
051            // Pretty print JSON (better render than JSONUtils)
052            String jsonString = __GSON.toJson(result);
053            value = jsonString;
054        }
055        catch (Exception e)
056        {
057            value = String.valueOf(result);
058        }
059        
060        return String.format("<pre>%s</pre>", value);
061    }
062    
063    static String htmlFormatStacktrace(String errorStacktrace)
064    {
065        String htmlStacktrace = errorStacktrace;
066        for (String[] replacement : __STACKTRACE_REPLACEMENTS)
067        {
068            htmlStacktrace = StringUtils.replace(htmlStacktrace, replacement[0], replacement[1], -1);
069        }
070        return htmlStacktrace;
071    }
072}