john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

Report 0.6

// 2012-10-23 johnpfeiffer requires Password, StorageReport, StorageGatewayDAO, StorageGateway, NetworkAccountDAO, NetworkAccount
// TODO: jsp's , sort by column header

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.UUID;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Report extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    private static final String CLASSVERSION = "0.6";
    private static final String PARAMLOGINUSERPASSWORD = "userPassword";
    private static final String PARAMLOGINBUTTON = "login";
    private static final String PARAMLOGOUTBUTTON = "logout";

    private static final String PARAMREPORTBUTTON = "report";
    private static final String PARAMREPORT = "reportradio";
    private static final String PARAMSTORAGEFILTER = "storagefilter";

    private static final String REPORTREFRESH = "refresh";
    private static final String REPORTSTORAGE = "storage";
    private static final String REPORTAUTHENTICATION = "authentication";

    private static final String FILTERMORPHEUS = "MORPHEUS";
    private static final String FILTERATMOS = "ATMOS";

    private static final String FORMSTYLE = "style ='margin: 0px; padding: 0px;'";
    private static final String LOGOUTFORMSTYLE = "style ='margin: 0px; padding: 0px;'";

    private static String servletURL;
    private ArrayList <String> authorizedTokens;

    private static final String STATICPASSWORD = "4reporting";
    private ArrayList <String> reportAuthentication;
    private ArrayList <String> storageReport;
    private int storageGatewayCount;
    private String lastRefresh;

    // Uses a static password so does not need to init
    public void init( ServletConfig config ) throws ServletException
    {
        super.init( config );
        authorizedTokens = new ArrayList <String>();
        writeToLog( "Report version " + CLASSVERSION );
    }

    protected void doGet( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException
    {
        response.setContentType( "text/html" ); // MIME type
        PrintWriter servletresponse = null;
        try
        {
            servletresponse = response.getWriter();
        }catch( Exception e )
        {
            System.err.println( "Unable to create a PrintWriter" );
            e.printStackTrace();
            System.exit( 1 );
        }

        HttpSession session = request.getSession( true );
        String contextPath = request.getContextPath();
        String servletName = getServletName();
        servletURL = contextPath + "/" + servletName;

        servletresponse.println( getXHTMLHeader( "Report" ) );
        servletresponse.println( "<body>" );

        servletresponse.println( "servletName = " + servletName + "<br />" );
        servletresponse.println( "contextPath = " + contextPath + "<br />" );
        servletresponse.println( "servletURL = " + servletURL + "<br />" );

        String sessionToken;
        String currentToken = "";
        if( session != null )
        {
            currentToken = (String) session.getAttribute( "sessionToken" );
        }

        String logout = request.getParameter( PARAMLOGOUTBUTTON );
        if( logout != null && !logout.isEmpty() && logout.equals( PARAMLOGOUTBUTTON ) )
        {
            logout = "";
            writeToLog( logoutCurrentUser( request , session , currentToken ) );
        }

        if( !authorizedTokens.contains( currentToken ) ) // validate start a session
        {
            String userPassword = request.getParameter( PARAMLOGINUSERPASSWORD );
            if( userPassword != null && !userPassword.isEmpty() && userPassword.equals( STATICPASSWORD ) )
            {
                userPassword = ""; // use the session, not the password
                session.setMaxInactiveInterval( 5 * 60 ); // 5 * 60 seconds = 5 minutes
                sessionToken = UUID.randomUUID().toString(); // SecureRandom based
                session.setAttribute( "sessionToken" , sessionToken );
                authorizedTokens.add( sessionToken );

                session = changeSessionIdentifier( request ); // security measure against session hijacking
                currentToken = (String) session.getAttribute( "sessionToken" );
                writeToLog( getUTCTimestamp() + " UTC Login successful: " + session.getId() + " , " + currentToken );
            }else
            {
                servletresponse.println( getLoginForm() );
            }
        }

        if( authorizedTokens.contains( currentToken ) ) // resume a session
        {
            servletresponse.println( "Version: " + CLASSVERSION + " <br /><br />" );

            // BEGIN APPLICATION SPECIFIC LOGIC HERE
            try
            {
                displayMenu( servletresponse );

                // get HTTP PARAMS
                String select = request.getParameter( PARAMREPORTBUTTON );
                String choice = request.getParameter( PARAMREPORT );
                String filter = request.getParameter( PARAMSTORAGEFILTER );

                if( select != null && !select.isEmpty() && select.equals( PARAMREPORTBUTTON ) )
                {
                    if( choice != null && !choice.isEmpty() )
                    {
                        if( choice.equals( REPORTSTORAGE ) )
                        {
                            displayStorageGatewayCount( servletresponse );
                            if( filter != null && !filter.isEmpty() && filter.equals( FILTERMORPHEUS ) )
                            {
                                displayStorageReport( servletresponse , FILTERMORPHEUS );
                            }else if( filter != null && !filter.isEmpty() && filter.equals( FILTERATMOS ) )
                            {
                                displayStorageReport( servletresponse , FILTERATMOS );
                            }else
                            {
                                displayStorageReport( servletresponse , "" );
                            }

                        }else if( choice.equals( REPORTAUTHENTICATION ) )
                        {
                            displayReportAuthentication( servletresponse , "" );

                        }else if( choice.equals( REPORTREFRESH ) )
                        {
                            servletresponse.println( "<br />" + getUTCTimestamp() + "UTC starting to load data... <br /><br />" );
                            try
                            {
                                refreshData();
                                lastRefresh = getUTCTimestamp() + " UTC";
                                System.out.println( lastRefresh + " Data refreshed" ); // tomcat6 writes to catalina.out
                                servletresponse.println( lastRefresh + " data refresh complete <br />" );
                            }catch( SQLException sqle )
                            {
                                servletresponse.println( "Error: " + sqle.getMessage() + "<br />" );
                                System.err.println( "Error: " + sqle.getMessage() );
                            }
                        }else
                        {
                            servletresponse.println( "Error: invalid Report Menu selection. <br />" );
                        }
                    }
                }

            }catch( Exception ioe )
            {
                System.out.println( ioe.getMessage() );
                servletresponse.println( ioe.getMessage() );
            }
            // END APPLICATION SPECIFIC LOGIC

            servletresponse.println( "<br />" );
            servletresponse.println( getLogoutForm() );
        }

        servletresponse.println( "</body></html>" );
        servletresponse.close();

    } // end doGet()

    // BEGIN APPLICATION SPECIFIC METHODS

    private void refreshData() throws Exception
    {
        StorageReport sr = new StorageReport();
        reportAuthentication = sr.getAuthenticationReport();
        // this.storageReport = sr.get();
        // this.storageGatewayCount = sr.getStorageGatewayCount();
    }

    private void displayStorageGatewayCount( PrintWriter out )
    {
        if( storageReport != null )
        {
            out.println( "<br /> " + storageGatewayCount + " StorageGateways found. <br />" );
        }
    }

    private String filterURLDefinition( String filter , String filterDescription )
    {
        String link = "<a href='" + servletURL + "?" + PARAMREPORTBUTTON + "=" + PARAMREPORTBUTTON + "&" + PARAMREPORT + "=" + REPORTSTORAGE + "&"
                + PARAMSTORAGEFILTER + "=" + filter + "'>" + filterDescription + "</a>";
        return link;
    }

    private void displayReportAuthentication( PrintWriter out , String filter )
    {
        if( reportAuthentication != null )
        {
            out.println( "<br /><em>Last data refresh: " + lastRefresh + "</em><br />" );
            ListIterator <String> it = reportAuthentication.listIterator();

            /*
             * out.println( "<br /><strong> FILTERS: </strong>" );
             * out.println( filterURLDefinition( FILTERMORPHEUS , "DeviceType = Morpheus Only" ) + " , " + filterURLDefinition( FILTERATMOS , "DeviceType = Atmos Only" )
             * + "<br /><br />" );
             */
            out.println( "<table border='1'> " );
            // TODO: first row are the headers

            int resultsCount = 0;
            while( it.hasNext() )
            {
                String row = it.next();
                if( row.contains( filter ) )
                {
                    resultsCount++;
                    out.print( "<tr> " );
                    out.print( "<td> " );
                    row = row.replace( "," , "</td><td>" );
                    out.print( row );
                    out.print( "</td> " );
                    out.print( "</tr> " );
                    out.println();
                }
            }
            out.println( "</table> " );
            out.println( resultsCount + " results found <br />" );
        }else
        {
            out.println( "<br />No data has been loaded, try to Refresh the Report Data <br />" );
        }
    }

    private void displayStorageReport( PrintWriter out , String filter )
    {
        if( storageReport != null )
        {
            out.println( "<br /><em>Last data refresh: " + lastRefresh + "</em><br />" );
            ListIterator <String> it = storageReport.listIterator();

            out.println( "<br /><strong> FILTERS: </strong>" );
            out.println( filterURLDefinition( FILTERMORPHEUS , "DeviceType = Morpheus Only" ) + " , " + filterURLDefinition( FILTERATMOS , "DeviceType = Atmos Only" )
                    + "<br /><br />" );

            out.println( "<table border='1'> " );
            if( it.hasNext() )
                ; // first row are the headers
            {
                String row = it.next();

                out.print( "<tr> " );
                out.print( "<th> " );
                row = row.replace( "," , "</th><th>" );
                out.print( row );
                out.print( "</th> " );
                out.print( "</tr> " );
                out.println();
            }

            int resultsCount = 0;
            while( it.hasNext() )
            {
                String row = it.next();
                if( row.contains( filter ) )
                {
                    resultsCount++;
                    out.print( "<tr> " );
                    out.print( "<td> " );
                    row = row.replace( "," , "</td><td>" );
                    out.print( row );
                    out.print( "</td> " );
                    out.print( "</tr> " );
                    out.println();
                }
            }
            out.println( "</table> " );
            out.println( resultsCount + " results found <br />" );
        }else
        {
            out.println( "<br />No data has been loaded, try to Refresh the Report Data <br />" );
        }
    }

    private void displayMenu( PrintWriter out )
    {
        out.println( "<form id='" + PARAMREPORTBUTTON + "' action='" + servletURL + "' method='post' >" );
        out.println( "<span><input type='submit' name='" + PARAMREPORTBUTTON + "' value='" + PARAMREPORTBUTTON + "'/></span>" );
        out.println( "<label><input type='radio' name='" + PARAMREPORT + "' value='" + REPORTSTORAGE + "' /> " + REPORTSTORAGE + "</label>" );
        out.println( "<label><input type='radio' name='" + PARAMREPORT + "' value='" + REPORTAUTHENTICATION + "' /> " + REPORTAUTHENTICATION + "</label>" );
        out.println( "<label><input type='radio' name='" + PARAMREPORT + "' value='" + REPORTREFRESH + "' /> refresh data " );
        if( lastRefresh!= null)
        {
            out.println( "<em> ( " + lastRefresh + " ) </em>" );
        }
        out.println( "</label>" );
        out.println( "</form>" );
    }

    // END APPLICATION SPECIFIC METHODS

    // GENERIC HELPER METHODS
    private HttpSession changeSessionIdentifier( HttpServletRequest request )
    {
        HttpSession session = request.getSession();
        HashMap <String , Object> attributes = new HashMap <String , Object>();

        Enumeration <String> attributeNames = (Enumeration <String>) session.getAttributeNames();
        while( attributeNames != null && attributeNames.hasMoreElements() )
        {
            String name = attributeNames.nextElement();
            Object value = session.getAttribute( name );
            attributes.put( name , value );
        }
        session.invalidate();
        HttpSession newSession = request.getSession();
        Set <Map.Entry <String , Object>> attributeValues = attributes.entrySet();
        Iterator <Map.Entry <String , Object>> it = attributeValues.iterator(); // copy back the session content
        while( it.hasNext() )
        {
            Map.Entry <String , Object> entry = it.next();
            newSession.setAttribute( (String) entry.getKey() , entry.getValue() );
        }
        return newSession;
    }

    private String getUTCTimestamp()
    {
        long currentTimeMilliseconds = System.currentTimeMillis();
        Date now = new Date( currentTimeMilliseconds );
        SimpleDateFormat utcFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
        utcFormat.setTimeZone( TimeZone.getTimeZone( "UTC" ) );
        return utcFormat.format( now );
    }

    private void writeToLog( String content )
    {
        System.out.println( content ); // tomcat defaults to catalina.out
    }

    // side effect to the session?
    private String logoutCurrentUser( HttpServletRequest request , HttpSession session , String currentToken )
    {
        StringBuilder strb = new StringBuilder();
        if( session != null )
        {
            while( authorizedTokens.contains( currentToken ) )
            {
                authorizedTokens.remove( currentToken );
            }
            if( request.isRequestedSessionIdValid() == true )
            {
                strb.append( getUTCTimestamp() + " UTC " + session.getId() + " , " + currentToken + " Logged out." );
                session.invalidate();
            }else
            {
                strb.append( "Logged out.  Session is invalidated." );
            }
        }
        return strb.toString();
    }

    private static String getLogoutForm()
    {
        StringBuilder strb = new StringBuilder();
        String newline = System.getProperty( "line.separator" );
        strb.append( "<form " + LOGOUTFORMSTYLE + " id='" + PARAMLOGOUTBUTTON + "' action='" + servletURL + "' method='post' >" + newline );
        strb.append( "<div><input type='submit' name='" + PARAMLOGOUTBUTTON + "' value='" + PARAMLOGOUTBUTTON + "' /></div>" + newline );
        strb.append( "</form>" + newline );
        return strb.toString();
    }

    private static String getLoginForm()
    {
        StringBuilder strb = new StringBuilder();
        String newline = System.getProperty( "line.separator" );
        strb.append( "<form " + FORMSTYLE + " id='" + PARAMLOGINBUTTON + "' action='" + servletURL + "' method='post' >" + newline );
        strb.append( "Password: &nbsp; <input type='password' name='" + PARAMLOGINUSERPASSWORD + "' id='" + PARAMLOGINUSERPASSWORD + "' /> <br /><br />" + newline );
        strb.append( "<span><input type='submit' name='" + PARAMLOGINBUTTON + "' value='" + PARAMLOGINBUTTON + "'/></span>" + newline );
        strb.append( "</form>" + newline );
        // strb.append( "<script type='text/javascript'> document.forms[ '"+ PARAMLOGINBUTTON + "' ].elements[ '" + PARAMLOGINUSERPASSWORD +
        // "' ].focus(); </script>" + newline );
        strb.append( "<script type='text/javascript'> document.getElementById( '" + PARAMLOGINUSERPASSWORD + "' ).focus(); </script>" );
        return strb.toString();
    }

    private static String getXHTMLHeader( String title )
    {
        StringBuilder strb = new StringBuilder();
        String newline = System.getProperty( "line.separator" );
        strb.append( "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">" + newline );
        strb.append( "<html xmlns=\"http://www.w3.org/1999/xhtml\">" + newline );
        strb.append( "<head><title>" + title + "</title>" + newline );
        strb.append( "<meta http-equiv='Content-Type' content='text/html;charset=utf-8' />" + newline );
        strb.append( "<link type='text/css' rel='stylesheet' href='css/style.css' />" + newline );
        // strb.append( "<script type='text/javascript' src='" + contextPath +
        // "/javascript.js'></script> + newline " );
        strb.append( "</head>" + newline );
        return strb.toString();
    }

    protected void doPost( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException
    {
        doGet( request , response );
    }
} // end class

  • « Report 0.6 StorageReport
  • Report 0.6 NetworkAccount »

Published

Oct 23, 2012

Category

java-servlet

~1192 words

Tags

  • 0.6 6
  • java-servlet 61
  • report 14