john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

AppProperties 1.2

// 2012-08-29 johnpfeiffer requires Password

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
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.Map;
import java.util.Map.Entry;
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 AppProperties extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    private static final String CLASSVERSION = "1.2";
    private static final String PARAMLOGINUSERPASSWORD = "userPassword";
    private static final String PARAMLOGINBUTTON = "login";
    private static final String PARAMLOGOUTBUTTON = "logout";

    private static final String CONFIGUREAUTHENTICATIONBUTTON = "configure-authentication";
    private static final String SAVEAUTHENTICATION = "save-authentication";

    private static final String CONFIGURECIFSSTORAGEBUTTON = "configure-cifs-storage";
    private static final String SAVECIFSBUTTON = "save-cifs";
    private static final String CONFIGUREATMOSSTORAGEBUTTON = "configure-atmos-storage";
    private static final String SAVEATMOSBUTTON = "save-atmos";
//  private static final String CONFIGURENIRVANIXSTORAGEBUTTON = "configure-nirvanix-storage";
//  private static final String SAVENIRVANIXBUTTON = "save-nirvanix";

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

    Password loginPassword = null;
    private static String servletURL;
    private ArrayList <String> authorizedTokens;
    StorageGatewayServiceDAO storageGatewayServiceDAO = null;

    private HashMap <Character , Character> illegalCharacterMap;

    public void init( ServletConfig config ) throws ServletException
    {
        super.init( config );
        authorizedTokens = new ArrayList <String>();
        writeToLog( "AppProperties version " + CLASSVERSION );
        loginPassword = new Password( 8 );
        illegalCharacterMap = new HashMap <Character , Character>();
        illegalCharacterMap.put( '<' , '<' );
        illegalCharacterMap.put( '>' , '>' );

        writeToLog( "One time use login password: " + loginPassword.get() );
    }

    protected void doGet( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException
    {
        String contextPath = request.getContextPath();
        String servletName = getServletName();
        servletURL = contextPath + "/" + servletName;
        String sessionToken;

        response.setContentType( "text/html" ); // MIME type
        PrintWriter servletresponse = null;
        try
        {
            servletresponse = response.getWriter();
        }catch( Exception e )
        {
            writeToLog( "ERROR: Unable to create a PrintWriter" );
            e.printStackTrace();
            System.exit( 1 );
        }

        HttpSession session = request.getSession( true );
        servletresponse.println( getXHTMLHeader( "Configuration" ) );
        servletresponse.println( "<body style ='margin: 20px; padding: 0px;'>" );
        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, accidentally keeping an extra token from login?
        {
            String userPassword = request.getParameter( PARAMLOGINUSERPASSWORD );
            if( loginPassword.isValid( userPassword ) )
            {
                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 );
                loginPassword = new Password( 8 );
                writeToLog( "One time use login password: " + loginPassword.get() );
            }else
            {
                servletresponse.println( getLoginForm() );
            }
        }

        if( authorizedTokens.contains( currentToken ) ) // resume a session
        {
            // servletresponse.println( "Version: " + CLASSVERSION + " <br /><br />" );
            // BEGIN APPLICATION SPECIFIC LOGIC HERE
            try
            {
                servletresponse.println( getMainMenu() );

                String configureAuthentication = request.getParameter( CONFIGUREAUTHENTICATIONBUTTON );
                if( configureAuthentication != null && !configureAuthentication.isEmpty() && configureAuthentication.equals( CONFIGUREAUTHENTICATIONBUTTON ) )
                {
                    servletresponse.println( getAuthenticationMenu() );
                }
                String authSaveButton = request.getParameter( SAVEAUTHENTICATION );
                if( authSaveButton != null && !authSaveButton.isEmpty() && authSaveButton.equals( SAVEAUTHENTICATION ) )
                {
                    String result = saveAuthgatewayService( request );
                    servletresponse.println( "<br />" + result + "<br />" );
                    writeToLog( result );
                    result = testAuthenticationConnection();
                    servletresponse.println( "<br />" + result + "<br />" );
                    writeToLog( result );
                    servletresponse.println( getAuthenticationMenu() );
                }

                String configureCIFSStorage = request.getParameter( CONFIGURECIFSSTORAGEBUTTON );
                if( configureCIFSStorage != null && !configureCIFSStorage.isEmpty() && configureCIFSStorage.equals( CONFIGURECIFSSTORAGEBUTTON ) )
                {
                    servletresponse.println( getCIFSStorageMenu() );
                }
                String cifsSaveButton = request.getParameter( SAVECIFSBUTTON );
                if( cifsSaveButton != null && !cifsSaveButton.isEmpty() && cifsSaveButton.equals( SAVECIFSBUTTON ) )
                {
                    String result = saveCIFS( request );
                    servletresponse.println( "<br />" + result + "<br />" );
                    writeToLog( result );
                    servletresponse.println( getCIFSStorageMenu() );
                }

                String configureAtmosStorage = request.getParameter( CONFIGUREATMOSSTORAGEBUTTON );
                if( configureAtmosStorage != null && !configureAtmosStorage.isEmpty() && configureAtmosStorage.equals( CONFIGUREATMOSSTORAGEBUTTON ) )
                {
                    servletresponse.println( getAtmosStorageMenu() );
                }
                String atmosSaveButton = request.getParameter( SAVEATMOSBUTTON );
                if( atmosSaveButton != null && !atmosSaveButton.isEmpty() && atmosSaveButton.equals( SAVEATMOSBUTTON ) )
                {
                    String result = saveAtmos( request );
                    servletresponse.println( "<br />" + result + "<br />" );
                    writeToLog( result );
                    servletresponse.println( getAtmosStorageMenu() );
                }

                /*
                String configureNirvanixStorage = request.getParameter( CONFIGURENIRVANIXSTORAGEBUTTON );
                if( configureNirvanixStorage != null && !configureNirvanixStorage.isEmpty() && configureNirvanixStorage.equals( CONFIGURENIRVANIXSTORAGEBUTTON ) )
                {
                    servletresponse.println( getNirvanixStorageMenu() );
                }
                String nirvanixSaveButton = request.getParameter( SAVENIRVANIXBUTTON );
                if( nirvanixSaveButton != null && !nirvanixSaveButton.isEmpty() && nirvanixSaveButton.equals( SAVENIRVANIXBUTTON ) )
                {
                    String result = saveNirvanix( request );
                    servletresponse.println( "<br />" + result + "<br />" );
                    writeToLog( result );
                    servletresponse.println( getNirvanixStorageMenu() );
                }
*/
            }catch( Exception e )
            {
                writeToLog( e.getMessage() );
                servletresponse.println( e.getMessage() );
            }
            // END APPLICATION SPECIFIC LOGIC

            servletresponse.println( "<br />" );
            servletresponse.println( getLogoutForm() );
        }
        servletresponse.println( "</body></html>" );
        servletresponse.close();
    } // end doGet()

    // BEGIN APPLICATION SPECIFIC METHODS

    private String getMainMenu()
    {
        StringBuilder strb = new StringBuilder();
        strb.append( "<form " + FORMSTYLE + " action='" + servletURL + "' method='post' >" );
        if( isAuthenticationEnabled() )
        {
            strb.append( "<span><input type='submit' name='" + CONFIGUREAUTHENTICATIONBUTTON + "' value='" + CONFIGUREAUTHENTICATIONBUTTON + "'/></span>" );
        }
        if( isCIFSStorageEnabled() )
        {
            strb.append( "<span><input type='submit' name='" + CONFIGURECIFSSTORAGEBUTTON + "' value='" + CONFIGURECIFSSTORAGEBUTTON + "'/></span>" );
        }
        if( isAtmosStorageEnabled() )
        {
            strb.append( "<span><input type='submit' name='" + CONFIGUREATMOSSTORAGEBUTTON + "' value='" + CONFIGUREATMOSSTORAGEBUTTON + "'/></span>" );
        }
/*
        if( isNirvanixStorageEnabled() )
        {
            strb.append( "<span><input type='submit' name='" + CONFIGURENIRVANIXSTORAGEBUTTON + "' value='" + CONFIGURENIRVANIXSTORAGEBUTTON + "'/></span>" );
        }
*/
        strb.append( "</form>" );
        return strb.toString();
    }

    private String getAuthenticationMenu()
    {
        StringBuilder strb = new StringBuilder();
        if( isAuthenticationEnabled() )
        {
            AuthgatewayServiceDAO authPropertiesDAO = null;
            try
            {
                authPropertiesDAO = new AuthgatewayServiceDAO();
                strb.append( "<form " + FORMSTYLE + " id='" + SAVEAUTHENTICATION + "' action='" + servletURL + "' " + authPropertiesDAO.getHTMLFormOnSubmitFunctionCall()
                        + " method='post' >" );
                strb.append( "<br />" + authPropertiesDAO.getHTMLForm() );
                strb.append( "<div><input type='submit' name='" + SAVEAUTHENTICATION + "' value='" + SAVEAUTHENTICATION + "'/></div>" );
                strb.append( "</form>" );
                strb.append( authPropertiesDAO.getValidateFormOnSubmit() );
            }catch( InstantiationException e )
            {
                writeToLog( e.getMessage() );
                strb.append( e.getMessage() );
            }
        }else
        {
            strb.append( "Authentication is not enabled" );
        }
        return strb.toString();
    }

    private String testAuthenticationConnection()
    {
        StringBuilder strb = new StringBuilder();
        if( isAuthenticationEnabled() )
        {
            AuthgatewayServiceDAO authPropertiesDAO = null;
            try
            {
                authPropertiesDAO = new AuthgatewayServiceDAO();
                strb.append( authPropertiesDAO.TestConnection( "service1" ) );
            }catch( InstantiationException e )
            {
                writeToLog( e.getMessage() );
                strb.append( e.getMessage() );
            }
        }
        return strb.toString();
    }

    private String saveAuthgatewayService( HttpServletRequest request )
    {
        StringBuilder strb = new StringBuilder();
        String newline = "<br />" + System.getProperty( "line.separator" );

        HashMap <String , String> parameterMap = new HashMap <String , String>();
        parameterMap.put( AuthgatewayService.PARAMACTIVE , request.getParameter( AuthgatewayService.PARAMACTIVE ) );
        parameterMap.put( AuthgatewayService.PARAMHOST , request.getParameter( AuthgatewayService.PARAMHOST ) );
        parameterMap.put( AuthgatewayService.PARAMPORT , request.getParameter( AuthgatewayService.PARAMPORT ) );
        parameterMap.put( AuthgatewayService.PARAMBASEDN , request.getParameter( AuthgatewayService.PARAMBASEDN ) );
        parameterMap.put( AuthgatewayService.PARAMUSERDN , request.getParameter( AuthgatewayService.PARAMUSERDN ) );
        parameterMap.put( AuthgatewayService.PARAMUSERDNPASSWORD , request.getParameter( AuthgatewayService.PARAMUSERDNPASSWORD ) );
        parameterMap.put( AuthgatewayService.PARAMSEARCHBASE , request.getParameter( AuthgatewayService.PARAMSEARCHBASE ) );
        parameterMap.put( AuthgatewayService.PARAMLDAPUSERATTRIBUTE , request.getParameter( AuthgatewayService.PARAMLDAPUSERATTRIBUTE ) );
        parameterMap.put( AuthgatewayService.PARAMSEARCHSUBTREE , request.getParameter( AuthgatewayService.PARAMSEARCHSUBTREE ) );

        Set <Map.Entry <String , String>> set = parameterMap.entrySet();
        Iterator <Map.Entry <String , String>> it = set.iterator();
        while( it.hasNext() )
        {
            Entry <String , String> e = it.next();
            String key = e.getKey();
            String value = e.getValue();
            if( value == null || value.isEmpty() )
            {
                if( key.equals( AuthgatewayService.PARAMSEARCHBASE ) || key.equals( AuthgatewayService.PARAMSEARCHSUBTREE ) )
                {
                    if( value == null )
                    {
                        parameterMap.put( key , "" ); // allow these fields to be blank (but not null)
                    }
                }else
                {
                    strb.append( "ERROR: " + key + " entry is missing." + newline );
                }
            }else
            {
                parameterMap.put( key , value.trim() ); // remove whitespace
                if( JohnStringUtils.containsIllegalCharacter( value , illegalCharacterMap ) )
                {
                    strb.append( "ERROR: " + key + " contains an illegal character < or >" + newline );
                }
            }
        }

        if( strb.toString().isEmpty() )
        {
            try
            {
                AuthgatewayServiceDAO authProperties = new AuthgatewayServiceDAO();
                authProperties.saveService( parameterMap );
                strb.append( "Settings saved successfully." + newline );
            }catch( IllegalArgumentException iae )
            {
                strb.append( iae.getMessage() );
            }catch( IOException ioe )
            {
                strb.append( ioe.getMessage() );
            }catch( InstantiationException e )
            {
                writeToLog( e.getMessage() );
                strb.append( e.getMessage() );
            }

        }else
        {
            strb.append( " Settings not saved." + newline );
        }
        return strb.toString();
    }

    private String getCIFSStorageMenu()
    {
        StringBuilder strb = new StringBuilder();
        if( isCIFSStorageEnabled() )
        {
            try
            {
                storageGatewayServiceDAO = new StorageGatewayServiceDAO.Builder().build();
                if( storageGatewayServiceDAO == null )
                {
                    throw new InstantiationException( "ERROR: unable to load configuration files" );
                }
            }catch( InstantiationException e )
            {
                writeToLog( "ERROR: InstantiationException " + e.getMessage() );
                strb.append( "ERROR: InstantiationException " + e.getMessage() );
            }
            strb.append( "<form " + FORMSTYLE + " id='" + SAVECIFSBUTTON + "' action='" + servletURL + "' method='post' >" );
            strb.append( "<br />" + storageGatewayServiceDAO.getHTMLForm( CIFSService.CIFSTORAGETYPE ) );
            strb.append( "<div><input type='submit' name='" + SAVECIFSBUTTON + "' value='" + SAVECIFSBUTTON + "'/></div>" );
            strb.append( "</form>" );
        }else
        {
            strb.append( "CIFS Storage is not enabled" );
        }
        return strb.toString();
    }

    private String saveCIFS( HttpServletRequest request )
    {
        StringBuilder strb = new StringBuilder();
        String oid = request.getParameter( StorageGatewayService.PARAMOID );
        String hash = request.getParameter( StorageGatewayService.PARAMHASH );
        String domain = request.getParameter( StorageGatewayService.PARAMDOMAIN );
        String type = request.getParameter( StorageGatewayService.PARAMSTORAGETYPE );
        if( type == null )
        {
            strb.append( "Storage Type not set so unable to save" );
        }else if( type.equals( CIFSService.CIFSTORAGETYPE ) )
        {
            try
            {
                String CIFSShare = request.getParameter( CIFSService.PARAMCIFSSHARE );
                String user = request.getParameter( CIFSService.PARAMCIFSUSER );
                String password = request.getParameter( CIFSService.PARAMCIFSPASSWORD );
                CIFSService newCIFS = new CIFSService.Builder().cifsshare( CIFSShare ).user( user ).password( password ).build();
                this.storageGatewayServiceDAO = new StorageGatewayServiceDAO.Builder().oid( oid ).hash( hash ).domain( domain ).cifs( newCIFS ).build();
                strb.append( storageGatewayServiceDAO.saveService() );
            }catch( IllegalArgumentException iae )
            {
                strb.append( iae.getMessage() );
            }catch( InstantiationException e )
            {
                strb.append( e.getMessage() );
            }
        }
        return strb.toString();
    }

    private String getAtmosStorageMenu()
    {
        StringBuilder strb = new StringBuilder();
        if( isAtmosStorageEnabled() )
        {
            try
            {
                storageGatewayServiceDAO = new StorageGatewayServiceDAO.Builder().build();
                if( storageGatewayServiceDAO == null )
                {
                    throw new InstantiationException( "ERROR: unable to load configuration files" );
                }
            }catch( InstantiationException e )
            {
                writeToLog( "ERROR: InstantiationException " + e.getMessage() );
                strb.append( "ERROR: InstantiationException " + e.getMessage() );
            }
            strb.append( "<form " + FORMSTYLE + " id='" + SAVEATMOSBUTTON + "' action='" + servletURL + "' "
                    + this.storageGatewayServiceDAO.getHTMLFormOnSubmitFunctionCall() + " method='post' >" );
            strb.append( "<br />" + storageGatewayServiceDAO.getHTMLForm( AtmosService.ATMOSSTORAGETYPE ) );
            strb.append( "<div><input type='submit' name='" + SAVEATMOSBUTTON + "' value='" + SAVEATMOSBUTTON + "'/></div>" );
            strb.append( "</form>" );
        }else
        {
            strb.append( "Atmos Storage is not enabled" );
        }
        return strb.toString();
    }

    private String saveAtmos( HttpServletRequest request )
    {
        StringBuilder strb = new StringBuilder();
        String oid = request.getParameter( StorageGatewayService.PARAMOID );
        String hash = request.getParameter( StorageGatewayService.PARAMHASH );
        String domain = request.getParameter( StorageGatewayService.PARAMDOMAIN );
        String type = request.getParameter( StorageGatewayService.PARAMSTORAGETYPE );
        if( type == null )
        {
            strb.append( "Storage Type not set so unable to save" );
        }else
        {
            try
            {
                String hostname = request.getParameter( AtmosService.PARAMEMCIPADDRESS );
                String portString = request.getParameter( AtmosService.PARAMEMCPORT );
                int emcPort = Integer.parseInt( portString );
                String uid = request.getParameter( AtmosService.PARAMEMCUID );
                String sharedsecret = request.getParameter( AtmosService.PARAMEMCSHAREDSECRET );
                AtmosService newAtmos = new AtmosService.Builder().isAvailable( true ).hostname( hostname ).port( emcPort ).uid( uid ).sharedSecret( sharedsecret ).build();
                this.storageGatewayServiceDAO = new StorageGatewayServiceDAO.Builder().oid( oid ).hash( hash ).domain( domain ).atmos( newAtmos ).build();
                strb.append( this.storageGatewayServiceDAO.saveService() );
            }catch( IllegalArgumentException iae )
            {
                strb.append( iae.getMessage() );
            }catch( InstantiationException e )
            {
                strb.append( e.getMessage() );
            }
        }
        return strb.toString();
    }

/*
    private String getNirvanixStorageMenu()
    {
        StringBuilder strb = new StringBuilder();
        if( isNirvanixStorageEnabled() )
        {
            try
            {
                this.storageGatewayServiceDAO = new StorageGatewayServiceDAO.Builder().build();
            }catch( InstantiationException e )
            {
                strb.append( "ERROR: InstantiationException " + e.getMessage() );
                writeToLog( "ERROR: InstantiationException " + e.getMessage() );
            }
            if( storageGatewayServiceDAO != null )
            {
                strb.append( "<form " + FORMSTYLE + " id='" + SAVENIRVANIXBUTTON + "' action='" + servletURL + "' "
                        + this.storageGatewayServiceDAO.getHTMLFormOnSubmitFunctionCall() + " method='post' >" );
                strb.append( "<br />" + this.storageGatewayServiceDAO.getHTMLForm( NirvanixService.NIRVANIXSTORAGETYPE ) );
                strb.append( "<div><input type='submit' name='" + SAVENIRVANIXBUTTON + "' value='" + SAVENIRVANIXBUTTON + "'/></div>" );
                strb.append( "</form>" );
            }
        }else
        {
            strb.append( "Nirvanix Storage is not enabled" );
        }
        return strb.toString();
    }

    private String saveNirvanix( HttpServletRequest request )
    {
        StringBuilder strb = new StringBuilder();
        String oid = request.getParameter( StorageGatewayService.PARAMOID );
        String hash = request.getParameter( StorageGatewayService.PARAMHASH );
        String domain = request.getParameter( StorageGatewayService.PARAMDOMAIN );
        String type = request.getParameter( StorageGatewayService.PARAMSTORAGETYPE );
        if( type == null )
        {
            strb.append( "Storage Type not set so unable to save" );
        }else
        {
            try
            {
                String apihostname = request.getParameter( NirvanixService.PARAMNIRVANIXAPIHOSTNAME );
                String user = request.getParameter( NirvanixService.PARAMNIRVANIXUSERNAME );
                String password = request.getParameter( NirvanixService.PARAMNIRVANIXPASSWORD );
                String appkey = request.getParameter( NirvanixService.PARAMNIRVANIXAPPKEY );
                String appname = request.getParameter( NirvanixService.PARAMNIRVANIXAPPNAME );
                NirvanixService newNirvanix = new NirvanixService.Builder().isAvailable(true).apihostname( apihostname ).user( user ).password( password ).appkey( appkey )
                        .appname( appname ).build();
                this.storageGatewayServiceDAO = new StorageGatewayServiceDAO.Builder().oid( oid ).hash( hash ).domain( domain ).nirvanix( newNirvanix ).build();
                strb.append( this.storageGatewayServiceDAO.saveService() );
            }catch( IllegalArgumentException iae )
            {
                strb.append( iae.getMessage() );
            }catch( InstantiationException e )
            {
                strb.append( e.getMessage() );
            }
        }
        return strb.toString();
    }
*/

    private boolean isAuthenticationEnabled()
    {
        boolean result = false;
        File f = new File( AuthgatewayServiceDAO.AUTHGATEWAYAPPPROPERTIES );
        if( f.exists() )
        {
            result = true;
        }
        return result;
    }

    // TODO: make this more accurate
    private boolean isCIFSStorageEnabled()
    {
        boolean result = false;
        File f = new File( StorageGatewayServiceDAO.STORAGEGATEWAYAPPPROPERTIES );
        if( f.exists() )
        {
            result = true;
        }
        return result;
    }

    // TODO: make this more accurate
    private boolean isAtmosStorageEnabled()
    {
        boolean result = false;
        File f = new File( StorageGatewayServiceDAO.STORAGEGATEWAYAPPPROPERTIES );
        if( f.exists() )
        {
            result = true;
        }
        return result;
    }

    // END APPLICATION SPECIFIC METHODS

    // GENERIC HELPER METHODS
    private HttpSession changeSessionIdentifier( HttpServletRequest request )
    {
        HttpSession session = request.getSession();
        HashMap <String , Object> attributes = new HashMap <String , Object>();
        @SuppressWarnings( "unchecked" )
        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

  • « App properties read value requires java util
  • AppProperties AtmosService »

Published

Aug 30, 2012

Category

java-servlet

~1762 words

Tags

  • 1.2 2
  • appproperties 18
  • java-servlet 61