Skip to content

Instantly share code, notes, and snippets.

@mindc
Last active August 18, 2017 23:11
Show Gist options
  • Save mindc/a2ba44cd12afaf4eb54686333025d964 to your computer and use it in GitHub Desktop.
Save mindc/a2ba44cd12afaf4eb54686333025d964 to your computer and use it in GitHub Desktop.
Custom Tomcat ErrorPage for Apache FOP and PHP

Custom Tomcat ErrorPage for Apache FOP and PHP

Custom ErrorPage at webapps/fop/Error.jsp

<%@ page isErrorPage="true" %><%

boolean handled = false; // Set to true after handling the error

    // Get the PageContext
    if(pageContext != null) {

        // Get the ErrorData
        ErrorData ed = null;
        try {
            ed = pageContext.getErrorData();
        } catch(NullPointerException ne) {
            // If the error page was accessed directly, a NullPointerException
            // is thrown at (PageContext.java:514).
            // Catch and ignore it... it effectively means we can't use the ErrorData
        }

        // Display error details for the user
        if(ed != null) {
            Exception ex = pageContext.getException();
            out.println(ex.getMessage());
            handled = true;
        }
    }

    // Check if the error was handled
    if(!handled) {
    %>
        <p />No information about this error was available.
    <%
    }
%>

We append this to webapps/fop/WEB-INF/web.xml to web-app node

<error-page>
    <error-code>500</error-code>
    <location>/Error.jsp</location>
</error-page>

<error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/Error.jsp</location>
</error-page>

No we can easly detect FOP errors in PHP

    /**
     * Generates PDF document.
     *
     * @param string $xml Path to XML data file
     * @param string $xslt Path to XSLT stylesheet
     * @param string $pdf Path for generated PDF file
     *
     * @return string
     */

    static function getPDF($xml,$xslt,$pdf){

        $opts = array('http' =>
            array(
                'method' => 'GET',
                'max_redirects' => '0',
                'ignore_errors' => '1'
            )
        );
        $context = stream_context_create($opts);
        $stream = fopen('http://localhost:8080/fop/fop?xml=' . $xml . '&xslt=' . $xslt, 'r', false, $context);
        $headers = stream_get_meta_data($stream);

        if ( preg_match('/200/',$headers['wrapper_data'][0]) ) {
            file_put_contents($pdf,stream_get_contents($stream));
        } else {
            throw new \Exception(strip_tags(stream_get_contents($stream),"<p><b>"));
        }
        return $pdf;
    }

Personally I used this in JSONRPC requests

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment