Friday, March 8, 2013

Using Java to Wrap Really Long String With No Spaces

Creating reports using Jasper, I had a requirement to add a stack trace into the report if something failed. The problem I ran into was that the data in a stack trace tends to be really long with no spaces. The Jasper report would not display the data that went outside of the confines of the document and it couldn't wrap it without any spaces in it.

A quick and easy solution is to insert unicode Zero Width Space between each character so that Jasper can wrap it where ever it wants..

 /**Insert zero width space in to a string so that solid words (like stack trace will wrap nicely
     *
     * @param string
     * @return
     */
    public static String addZeroWidthSpace(String string) {
        char[] chars = string.toCharArray();
        StringBuilder builder = new StringBuilder(string.substring(0, 1));
        for (int i = 1; i < chars.length; i++) {
            builder.append("\u200B");
            builder.append(chars[i]);
        }
        return builder.toString();
    }


Pass your string through this method and turn Jasper Field markup to HTML and allow the field to wrap.

Happy Coding.

PrimeFaces File Download Status and IE (animated GIFs)

You might have notice that IE browsers will not animate a gif if they are loaded hidden.

I first saw this when making use of the PrimeFaces file download dialog. I wanted a status gif in a dialog. Worked fine on all browsers except IE of course.. here is a quick work around.

        <p:dialog modal="true" widgetVar="statusDialog" header="Status" draggable="false" closable="false" resizable="false"> 
             <div id="progressBar">
                <p:graphicImage value="/img/ajaxloadingbar.gif" /> 
           </div> 
        </p:dialog> 
 
        <h:form>
           
            <h:messages globalOnly="true" styleClass="error"/>

        <script type="text/javascript"> 
            function start() { 
                statusDialog.show();
              //hack to avoid annimated gifs not annimating in IE Browsers
                var isIE = /*@cc_on!@*/false;
                   if(isIE){
                    var pb = document.getElementById("progressBar");
                    pb.innerHTML = '<img src="/img/ajaxloadingbar.gif"/>';
                } 
            } 
             
            function stop() { 
                statusDialog.hide(); 
            } 
        </script>
            <div class="buttons">

               
                <p:commandLink id="downloadLink" type="submit" styleClass="btn btn-primary"
                        actionListener="#{foo.downloadAction()}"
                        value="Generate Report" ajax="false"
                        onclick="PrimeFaces.monitorDownload(start, stop)"  
                        icon="ui-icon-arrowthichk-s" >

                    <p:fileDownload value="#{foo.downloadContentProperty}" /> 
                </p:commandLink>