<%@ page import="com.atlassian.core.logging.DatedLoggingEvent" %>
<%@ page import="com.atlassian.core.logging.ThreadLocalErrorCollection" %>
<%@ page import="com.atlassian.jira.ComponentManager" %>
<%@ page import="com.atlassian.jira.plugin.JiraPluginManager" %>
<%@ page import="com.atlassian.jira.service.DefaultServiceManager" %>
<%@ page import="com.atlassian.jira.service.ServiceManager" %>
<%@ page import="com.atlassian.jira.util.ExceptionInterpreterUtil" %>
<%@ page import="com.atlassian.jira.util.system.SystemInfoUtils" %>
<%@ page import="com.atlassian.jira.util.system.SystemInfoUtilsImpl" %>
<%@ page import="com.atlassian.jira.web.action.admin.ViewSystemInfo" %>
<%@ page import="com.atlassian.jira.web.util.ExternalLinkUtil" %>
<%@ page import="com.atlassian.jira.web.util.ExternalLinkUtilImpl" %>
<%@ page import="com.atlassian.plugin.PluginAccessor" %>
<%@ page import="com.opensymphony.util.TextUtils" %>
<%@ page import="org.apache.log4j.Category" %>
<%@ page import="org.apache.log4j.spi.LoggingEvent" %>
<%@ page import="javax.servlet.ServletException" %>
<%@ page import="java.io.PrintWriter" %>
<%@ page import="java.io.StringWriter" %>
<%@ page import="java.util.*"%>
<%@ page import="org.ofbiz.core.entity.GenericValue"%>
<%@ page import="com.opensymphony.module.propertyset.PropertySet"%>
<%@ page import="com.atlassian.jira.service.JiraServiceContainer"%>
<%@ page import="com.atlassian.plugin.Plugin"%>
<%@ page import="com.atlassian.plugin.PluginInformation"%>
<%@ page import="com.opensymphony.user.User" %>
<%@ page import="com.atlassian.seraph.auth.DefaultAuthenticator" %>
<%@ page import="com.atlassian.jira.ManagerFactory" %>
<%@ page import="com.atlassian.jira.security.Permissions" %>
<%@ page isErrorPage="true" %>
<%@ taglib uri="webwork" prefix="webwork" %>

<html>
	<head>
	<title>Oops - an error has occurred</title>
    <%@ include file="/includes/decorators/stylesheettag.jsp" %>
    <script language="JavaScript" type="text/javascript" src="<%=request.getContextPath()%>/includes/js/cookieUtil.js"></script>
    <style type="text/css">
		h1 { color: #003366; text-align: left; margin: 0px 0px 30px 10px; padding: 0px; border-width: 0px 0px 1px 0px; border-style: solid; border-color: #003366;}
        p { padding: 5px 10px 5px 10px;}
		p.message { padding: 10px 30px 10px 30px; font-weight: bold; font-size: 130%; border-width: 1px; border-style: dashed; border-color: #336699; }
		p.description { padding: 10px 30px 20px 30px; border-width: 0px 0px 1px 0px; border-style: solid; border-color: #336699;}
		p.topped { padding: 5px 10px 5px 0px; margin: 0px 0px 0px 10px; border-width: 1px 0px 0px 0px; border-style: solid; border-color: #003366; }
        span.switch { cursor: pointer; margin-left: 5px; text-decoration: underline; }
        pre {padding: 5px 10px 5px 10px;}
   </style>
   </head>

   <%
       ExternalLinkUtil externalLinkUtil = new ExternalLinkUtilImpl();
       final SystemInfoUtils systemInfoUtils = (SystemInfoUtils) ComponentManager.getComponentInstanceOfType(SystemInfoUtilsImpl.class);
       final ViewSystemInfo vsi = new ViewSystemInfo(
               systemInfoUtils,
               (ServiceManager) ComponentManager.getComponentInstanceOfType(DefaultServiceManager.class),
               (PluginAccessor) ComponentManager.getComponentInstanceOfType(JiraPluginManager.class),
               ComponentManager.getInstance().getApplicationProperties());

       // orion does not support the exception object.
       boolean isOrion = "Orion".equals(systemInfoUtils.getAppServer());

       String line = "";
       String ex = null;

       if (isOrion)
       {
           ex = (String) request.getAttribute("javax.servlet.error.message");
           //get the first line of the error message for the "cause:"

           if (ex != null)
           {
               // this is a bit of a hack to get the message from the decorated exception
               if(ex.startsWith("<PRE>"))
               {
                   line = ex.substring(5, ex.length());
               }
               else
               {
                   line = ex;
               }
               line = line.substring(0, line.indexOf("<br>"));
           }
           else
               line = "No exception";

       }
       else
       {
           if (exception != null)
           {
               Throwable cause = exception;
               if (exception instanceof ServletException)
               {
                   Throwable rootCause = ((ServletException) exception).getRootCause();
                   if (rootCause != null)
                    cause = rootCause;
               }
               //log exception to the log files, so that it gets captured somewhere.
               Category.getInstance("500ErrorPage").error("Exception caught in 500 page " + cause.getMessage(), cause);
               line = cause.toString();
               StringWriter sw = new StringWriter();
               PrintWriter pw = new PrintWriter(sw);
               cause.printStackTrace(pw);
               ex = sw.toString();
           }
       }

       String interpretedMsg = ExceptionInterpreterUtil.execute(vsi, ex);

        // Check that the user has the global admin permission to see the services/listeners params (JRA-12081)
        HttpSession httpSession = request.getSession(false); //dont create the session if there isnt one
        User remoteUser = httpSession != null ? (User) httpSession.getAttribute(DefaultAuthenticator.LOGGED_IN_KEY) : null;
        boolean isGlobalAdmin = remoteUser != null && ManagerFactory.getPermissionManager().hasPermission(Permissions.ADMINISTER, remoteUser);
   %>

<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" >
<div id="Content">
<br>
<% if(interpretedMsg != null && !"".equals(interpretedMsg.trim()))
   {
%>

<h1><webwork:text name="'system.error.known.title'"/></h1>
<p><webwork:text name="'system.error.known.description'"/>
<p>
<webwork:text name="'system.error.known.resembles'"/>
<p>
<%= interpretedMsg %>
</p>
<p>
<webwork:text name="'system.error.known.notifyadmin'"/>

<% }
    else
   {
%>
<h1><webwork:text name="'system.error.unknown.title'"/></h1>
<p><webwork:text name="'system.error.unknown.description1'"/>
<p>
<webwork:text name="'system.error.unknown.description2'"/>
<% } %>

<p class="topped">
<webwork:text name="'system.error.unknown.description3'"><a href="<%= request.getContextPath() %>/secure/admin/jira/JiraSupportRequest!default.jspa" target="_blank">
<webwork:param name="'value0'"><a href="<%= request.getContextPath() %>/secure/admin/jira/JiraSupportRequest!default.jspa" target="_blank"></webwork:param>
<webwork:param name="'value1'"></a></webwork:param>
</webwork:text>

<p>
<webwork:text name="'system.error.unknown.description4'">
<webwork:param name="'value0'"><b></webwork:param>
<webwork:param name="'value1'"></b></webwork:param>
<webwork:param name="'value2'">
    <a href="<%= externalLinkUtil.getProperty("external.link.jira.support.site") %>"><%= externalLinkUtil.getProperty("external.link.jira.support.site") %></a>
</webwork:param>
</webwork:text>
<ol>
<li><webwork:text name="'system.error.step1'"/>
<li><webwork:text name="'system.error.step2'"/>
<li><webwork:text name="'system.error.step3'"><webwork:param name="'value0'"><% out.println(vsi.getLogPath());%></webwork:param></webwork:text>
</ol>
<p class="topped">

        <p>
        <b><webwork:text name="'system.error.cause'"/>: </b><br/>
        <%= line %>
        </p>
        <% if(ex != null)
        {
        %>
            <p>
            <b><webwork:text name="'system.error.stack.trace'"/>: </b> <span class="switch" id="stacktrace-switch" onclick="CookieUtil.toggleVisibility('stacktrace', '[show]', '[hide]', true)">[hide]</span>
            <pre id="stacktrace"><%= ex %></pre>
        <% }
            else
           { %>
            <p><%= request.getAttribute("javax.servlet.error.message") %></p>
        <% } %>
        <p><webwork:text name="'system.error.referer.url'"/>:
            <b><%= request.getHeader("Referer") != null ? request.getHeader("Referer") : "Unknown" %></b></p>
        <p>
        <b><webwork:text name="'system.error.build.information'"/>: </b><br/>
        <%
            final Map buildstats = vsi.getBuildStats();
            for (Iterator i = buildstats.entrySet().iterator(); i.hasNext();)
            {
                Map.Entry entry = (Map.Entry) i.next();
                %><%= entry.getKey() %>: <%= entry.getValue() %><br /><%
            }
        %>
        </p>
        <p>
        <b><webwork:text name="'system.error.server.information'"/>: </b><br/>
            <webwork:text name="'system.error.application.server'"/>: <%= application.getServerInfo() %><br>
            <webwork:text name="'system.error.servlet.version'"/>: <%= application.getMajorVersion() %>.<%= application.getMinorVersion() %><br>
        </p>

        <p>
        <b><webwork:text name="'system.error.file.paths'"/>:</b><br/>
           <webwork:text name="'system.error.location.of.entityengine'"/>: <%= vsi.getEntityEngineXmlPath()%><br>
           <webwork:text name="'system.error.location.of.log'"/>: <%= vsi.getLogPath()%><br/>
        </p>

        <p>
        <b><webwork:text name="'system.error.memory.information'"/>:</b><br/>
        <%
            final Map jvmStats = vsi.getJvmStats();
            for (Iterator i = jvmStats.entrySet().iterator(); i.hasNext();)
            {
                Map.Entry entry = (Map.Entry) i.next();
                %><%= entry.getKey() %>: <%= entry.getValue() %> MB<br /><%
            }
        %>
        </p>
        <p>
        <b><webwork:text name="'system.error.system.information'"/>:</b><br/>
        <%
            final Map sysinfo = vsi.getProps();
            for (Iterator i = sysinfo.entrySet().iterator(); i.hasNext();)
            {
                Map.Entry entry = (Map.Entry) i.next();
                %><%= entry.getKey() %>: <%= entry.getValue() %><br /><%
            }
        %>
        </p>

        <p>
        <b><webwork:text name="'system.error.request.information'"/>:</b><br/>
        <%
            try {
                String encodedQueryString = request.getQueryString() == null ? " " : TextUtils.htmlEncode(request.getQueryString());
        %>

            - <webwork:text name="'system.error.request.url'"/>: <%= request.getRequestURL() %><br>
            - <webwork:text name="'system.error.scheme'"/>: <%= request.getScheme() %><br>
            - <webwork:text name="'system.error.server'"/>: <%= request.getServerName() %><br>
            - <webwork:text name="'system.error.port'"/>: <%= request.getServerPort() %><br>
            - <webwork:text name="'system.error.uri'"/>: <%= request.getRequestURI() %><br>
            - <webwork:text name="'system.error.context.path'"/>: <%= request.getContextPath() %><br>
            - - <webwork:text name="'system.error.servlet.path'"/>: <%= request.getServletPath() %><br>
            - - <webwork:text name="'system.error.path.info'"/>: <%= request.getPathInfo() %><br>
            - - <webwork:text name="'system.error.query.string'"/>: <%= encodedQueryString %><br><br>

                <b><webwork:text name="'system.error.request.attributes'"/></b><br>
            <%
                Enumeration attributeNames = request.getAttributeNames();
                while (attributeNames.hasMoreElements())
                {
                    String name = (String) attributeNames.nextElement();
                    Object attribute = request.getAttribute(name);
                    %>
                    - <%= name %> : <%= TextUtils.htmlEncode(attribute == null ? "null" : attribute.toString()) %><br>
                    <%
                }
            %>
        <%
            }
            catch (Throwable t)
            {
                out.println("Error rendering logging information - uh oh.");
                t.printStackTrace(new PrintWriter(out));
            }
        %>
        </p>

        <p>
        <b><webwork:text name="'system.error.request.logging'"/></b><br/>
        <%
            try {
            List list = ThreadLocalErrorCollection.getList();
            %>
                <b><%= list.size() %></b> log statements generated by this request:<br>
            <%
            for (Iterator iterator = list.iterator(); iterator.hasNext();)
            {
                DatedLoggingEvent dle = (DatedLoggingEvent) iterator.next();
                LoggingEvent loggingEvent = dle.getEvent();
                Date date = dle.getDate();
                %>
<%-- Note that both of the logging fields have been deprecated. Using this for compatability with pre 1.2.6 logj. JRA-5405 --%>
                <font color="darkred">[<%= loggingEvent.level %>]</font>
                <font color="darkblue"><%= date.toString() %></font>
                [<%= loggingEvent.categoryName %>]
                <%= loggingEvent.getRenderedMessage() %>
                <br>
                <% if (loggingEvent.getThrowableInformation() != null) { %>
                    <div style="font-size: 10px; margin: 0 0 0 20px;">
                        <%
                            final String[] throwableStrRep = loggingEvent.getThrowableStrRep();
                            for (int i = 0; i < throwableStrRep.length && i < 20; i++)
                            {
                                String s = throwableStrRep[i];
                                out.println(s + "<br>");
                            }
                        %>
                    </div>
                <% } %>
                <%
            }
            }
            catch (Throwable t)
            {
                out.println("Error rendering logging information - uh oh.");
                t.printStackTrace(new PrintWriter(out));
            }
        %>
        </p>

<%-- LISTENERS - start --%>
<% try { %>
<p>
    <span style="font-weight:bold;"><webwork:text name="'admin.systeminfo.listeners'"/></span><br/>
    <%
        final Collection listeners = vsi.getListeners();
        for (Iterator i = listeners.iterator(); i.hasNext();)
        {
            GenericValue gv = (GenericValue) i.next();
    %>
    &nbsp;-&nbsp;<span style="font-weight:bold;"><%= gv.getString("name") %></span> (<%= gv.getString("clazz") %>)
    <%
        if (isGlobalAdmin)
        {
            final PropertySet propertySet = vsi.getPropertySet(gv);
            final Collection keys = propertySet.getKeys("", 5);
            if (keys != null && !keys.isEmpty())
            {
                for (Iterator j = keys.iterator(); j.hasNext();)
                {
                    String key = (String) j.next();
        %><br/>&nbsp;&nbsp;&nbsp;-&nbsp;<span style="font-weight:bold;"><%= key %>:</span> <%= propertySet.getString(key)%>
        <%
                }
            }
        }
    %>
    <br/>
    <%
        }
    %>
</p>
<%
}
catch (Exception e) {
    System.out.println("Error getting listeners");
    e.printStackTrace();
}
%>
<%-- LISTENERS - end --%>

<%-- SERVICES - start --%>
<%
    try { %>
<p>
    <span style="font-weight:bold;"><webwork:text name="'admin.systeminfo.services'"/></span><br/>
    <%
        final Collection services = vsi.getServices();
        for (Iterator i = services.iterator(); i.hasNext();)
        {
            JiraServiceContainer service = (JiraServiceContainer) i.next();
    %>
    &nbsp;-&nbsp;<span style="font-weight:bold;"><%= service.getName() %></span> (<%= service.getServiceClass() %>)<br/>
    &nbsp;&nbsp;&nbsp;-&nbsp;<span style="font-weight:bold;"><webwork:text
        name="'admin.systeminfo.service.delay'"/>:</span> <%= vsi.getMillisecondsToMinutes(service.getDelay()) %>
    <webwork:text name="'core.dateutils.minutes'"/><br/>
    <%
            if (isGlobalAdmin)
            {
            final Map servicePropertyMap = vsi.getServicePropertyMap(service);
            if (servicePropertyMap != null && !servicePropertyMap.isEmpty())
            {
                for (Iterator j = servicePropertyMap.entrySet().iterator(); j.hasNext();)
                {
                    Map.Entry entry = (Map.Entry) j.next();
        %>&nbsp;&nbsp;&nbsp;-&nbsp;<span
            style="font-weight:bold;"><%= entry.getKey() %>:</span> <%= vsi.getText((String) entry.getValue()) %><br/>
        <%
                    }
                }
            }
        }
    %>
</p>
<%
}
catch (Exception e) {
    System.out.println("Error getting services");
    e.printStackTrace();
}
%>
<%-- SERVICES - end --%>

<%-- PLUGINS - start --%>
<% try { %>
<p>
    <span style="font-weight:bold;"><webwork:text name="'admin.systeminfo.plugins'"/></span><br/>
    <%
        final Collection plugins = vsi.getPlugins();
        for (Iterator i = plugins.iterator(); i.hasNext();)
        {
            final Plugin plugin = (Plugin) i.next();
            final PluginInformation pluginInformation = plugin.getPluginInformation();
    %>
    &nbsp;-&nbsp;<span style="font-weight:bold;"><%= plugin.getName() %></span> <%= pluginInformation.getVersion() %> -
    <webwork:text name="'admin.systeminfo.plugin.by'"/>&nbsp;<%= pluginInformation.getVendorName() %><br/>
    <%
        if (vsi.isPluginEnabled(plugin))
        {
    %>
    &nbsp;&nbsp;&nbsp;-&nbsp;<webwork:text name="'admin.systeminfo.plugin.enabled'"/><br/>
    <%
    }
    else
    {
    %>
    &nbsp;&nbsp;&nbsp;-&nbsp;<webwork:text name="'admin.systeminfo.plugin.disabled'"/><br/>
    <%
        }
        final Map parameters = pluginInformation.getParameters();
        if (parameters != null && !parameters.isEmpty())
        {
            for (Iterator j = parameters.entrySet().iterator(); j.hasNext();)
            {
                Map.Entry entry = (Map.Entry) j.next();
    %>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;<span
        style="font-weight:bold;"><%= entry.getKey() %>:</span> <%= vsi.getText((String) entry.getValue()) %><br/>
    <%
                }
            }
        }
    %>
</p>
<%
}
catch (Exception e) {
    System.out.println("Error getting plugins");
    e.printStackTrace();
}
%>
<%-- PLUGINS - end --%>


</div>

</body>
</html>

