001    //$$Header: $$
002    /*----------------------------------------------------------------------------
003     This file is part of deegree, http://deegree.org/
004     Copyright (C) 2001-2009 by:
005       Department of Geography, University of Bonn
006     and
007       lat/lon GmbH
008    
009     This library is free software; you can redistribute it and/or modify it under
010     the terms of the GNU Lesser General Public License as published by the Free
011     Software Foundation; either version 2.1 of the License, or (at your option)
012     any later version.
013     This library is distributed in the hope that it will be useful, but WITHOUT
014     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
015     FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
016     details.
017     You should have received a copy of the GNU Lesser General Public License
018     along with this library; if not, write to the Free Software Foundation, Inc.,
019     59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
020    
021     Contact information:
022    
023     lat/lon GmbH
024     Aennchenstr. 19, 53177 Bonn
025     Germany
026     http://lat-lon.de/
027    
028     Department of Geography, University of Bonn
029     Prof. Dr. Klaus Greve
030     Postfach 1147, 53001 Bonn
031     Germany
032     http://www.geographie.uni-bonn.de/deegree/
033    
034     e-mail: info@deegree.org
035    ----------------------------------------------------------------------------*/
036    
037    package org.deegree.enterprise.servlet;
038    
039    import java.io.File;
040    import java.io.IOException;
041    import java.io.Serializable;
042    import java.util.UUID;
043    
044    import javax.servlet.ServletException;
045    import javax.servlet.http.HttpServlet;
046    import javax.servlet.http.HttpServletRequest;
047    import javax.servlet.http.HttpServletResponse;
048    import javax.servlet.http.HttpSession;
049    
050    import org.deegree.framework.log.ILogger;
051    import org.deegree.framework.log.LoggerFactory;
052    import org.deegree.framework.util.StringTools;
053    import org.deegree.framework.xml.XMLFragment;
054    import org.deegree.framework.xml.XSLTDocument;
055    import org.deegree.portal.owswatch.Constants;
056    import org.deegree.portal.owswatch.JSPagesReference;
057    import org.deegree.portal.owswatch.Messages;
058    import org.deegree.portal.owswatch.ServiceConfiguration;
059    import org.deegree.portal.owswatch.ServiceWatcher;
060    import org.deegree.portal.owswatch.ServiceWatcherFactory;
061    
062    /**
063     * Used to authenticate the user in order to view the Protocol file
064     *
065     * @author <a href="mailto:elmasry@lat-lon.de">Moataz Elmasry</a>
066     * @author last edited by: $Author: elmasry $
067     *
068     * @version $Revision: 1.3 $, $Date: 2008-03-07 16:31:02 $
069     */
070    public class ProtocolServlet extends HttpServlet implements Serializable {
071    
072        private static final ILogger LOG = LoggerFactory.getLogger( ProtocolServlet.class );
073    
074        private final String SESSIONID_KEY = Constants.SESSIONID_KEY;
075    
076        private ServiceWatcher watcher = null;
077    
078        private String webinfPath = null;
079    
080        private String confFilePath = null;
081    
082        private ServiceWatcherFactory factory = null;
083    
084        /**
085         *
086         */
087        private static final long serialVersionUID = -6509717095713986594L;
088    
089        /*
090         * (non-Javadoc)
091         *
092         * @see javax.servlet.GenericServlet#init()
093         */
094        @Override
095        public void init()
096                                throws ServletException {
097            confFilePath = this.getServletContext().getRealPath( this.getInitParameter( "owsWatchConfiguration" ) );
098            webinfPath = this.getServletContext().getRealPath( "WEB-INF/conf/owswatch" );
099            if ( !webinfPath.endsWith( "/" ) ) {
100                webinfPath = webinfPath.concat( "/" );
101            }
102            try {
103                factory = ServiceWatcherFactory.getInstance( confFilePath, webinfPath );
104                watcher = factory.getServiceWatcherInstance();
105            } catch ( Exception e ) {
106                LOG.logError( e.getLocalizedMessage() );
107                return;
108            }
109        }
110    
111        /*
112         * (non-Javadoc)
113         *
114         * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
115         *      javax.servlet.http.HttpServletResponse)
116         */
117        @Override
118        protected void doGet( HttpServletRequest request, HttpServletResponse response )
119                                throws ServletException, IOException {
120            PerformAction( request, response );
121        }
122    
123        /*
124         * (non-Javadoc)
125         *
126         * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
127         *      javax.servlet.http.HttpServletResponse)
128         */
129        @Override
130        protected void doPost( HttpServletRequest request, HttpServletResponse response )
131                                throws ServletException, IOException {
132            PerformAction( request, response );
133        }
134    
135        protected void PerformAction( HttpServletRequest request, HttpServletResponse response ) {
136    
137            String action = request.getParameter( "action" );
138            if ( action == null ) {
139                gotoErrorPage( request, response, "The action value is null", null, null );
140                return;
141            }
142            if ( action.equals( "loginProtocol" ) ) {
143                handleLoginProtocol( request, response );
144            } else if ( action.equals( "serviceProtocol" ) ) {
145                handleServiceProtocol( request, response );
146            } else {
147                gotoErrorPage( request, response, StringTools.concat( 100, "action: ", action,
148                                                                      " is unknown to this servlet" ), null, null );
149            }
150        }
151    
152        /**
153         * Handle login for Protocol requests
154         *
155         * @param request
156         * @param response
157         */
158        private boolean handleLoginProtocol( HttpServletRequest request, HttpServletResponse response ) {
159    
160            String user = request.getParameter( "username" );
161            String pwd = request.getParameter( "password" );
162            try {
163                if ( factory.getConf().isAuthenticatedUser( user, pwd ) ) {
164                    HttpSession session = request.getSession( true );
165                    // isLoggedin
166                    String sessionId = UUID.randomUUID().toString();
167                    session.setAttribute( SESSIONID_KEY, sessionId );
168                    String serviceId = (String) session.getAttribute( "serviceId" );
169                    String nextpage = StringTools.concat( 200, "wprotocol?action=serviceProtocol&serviceId=", serviceId,
170                                                          "&", SESSIONID_KEY, "=", sessionId );
171                    response.sendRedirect( nextpage );
172                } else {
173                    gotoErrorPage( request, response, Messages.getMessage( "INCORRECT_LOGIN" ),
174                                   Messages.getMessage( "MESSAGE_GOTO_MAIN" ),
175                                   JSPagesReference.getString( "OWSWatch.login" ) );
176                }
177            } catch ( Exception e ) {
178                String errorMsg = StringTools.concat( 100, Messages.getMessage( "ERROR_LOGIN" ), "</br>",
179                                                      e.getLocalizedMessage() );
180                gotoErrorPage( request, response, errorMsg, Messages.getMessage( "MESSAGE_GOTO_MAIN" ),
181                               JSPagesReference.getString( "OWSWatch.login" ) );
182                return false;
183            }
184            return true;
185        }
186    
187        /**
188         * forwards the Response to the error page
189         *
190         * @param request
191         * @param response
192         * @param error
193         * @param urlText
194         * @param url
195         */
196        private void gotoErrorPage( HttpServletRequest request, HttpServletResponse response, String error, String urlText,
197                                    String url ) {
198    
199            LOG.logError( error );
200            HttpSession session = request.getSession( true );
201    
202            session.setAttribute( "message", StringTools.replace( error, "\n", "<br/>", true ) );
203            if ( error == null ) {
204                error = "An unknown error has occured";
205            }
206            if ( urlText == null ) {
207                urlText = "";
208            }
209            session.setAttribute( "URLText", urlText );
210            if ( url == null ) {
211                url = "";
212            }
213            session.setAttribute( "URLAdd", url );
214            try {
215                String nextpage = JSPagesReference.getString( "OWSWatch.error" );
216                response.sendRedirect( nextpage );
217            } catch ( Exception e ) {
218                LOG.logError( "The page could not be redirected to the error page" );
219            }
220        }
221    
222        /**
223         * sends the protocol of a serviceMonitor identified by its protIndex (got from request.getParameter()) object has
224         * as html file to the browser
225         *
226         */
227        private boolean handleServiceProtocol( HttpServletRequest request, HttpServletResponse response ) {
228    
229            if ( watcher == null || !isLoggedIn( request ) ) {
230                String serviceId = request.getParameter( "serviceId" );
231                if ( serviceId == null ) {
232                    return handleLogout( request, response );
233                }
234                String sessionId = (String) request.getSession().getAttribute( SESSIONID_KEY );
235                request.getSession().setAttribute( "serviceId", serviceId );
236                if ( sessionId == null ) {
237                    String next = JSPagesReference.getString( "OWSWatch.protocolLogin" );
238                    // If the user is not logged in, this is to check that the user didn't just logged
239                    // in for another protocol, so that the user does not have to login everytime he
240                    // clicks a protocol link
241                    try {
242                        response.sendRedirect( next );
243                        return true;
244                    } catch ( IOException e ) {
245                        gotoErrorPage( request, response, Messages.getMessage( "ERROR_PAGE_NOT_FOUND", next ), null, null );
246                    }
247                }
248            }
249            int serviceId = Integer.parseInt( request.getParameter( "serviceId" ) );
250    
251            ServiceConfiguration serviceConfiguration = watcher.getService( serviceId );
252            if ( serviceConfiguration == null ) {
253                gotoErrorPage( request, response, Messages.getMessage( "ERROR_NULL_OBJ", "ServiceConfiguration" ),
254                               Messages.getMessage( "MESSAGE_GOTO_MAIN" ),
255                               JSPagesReference.getString( "OWSWatch.owswatchMonitorList" ) );
256                return false;
257            }
258    
259            String xmlURI = watcher.getServiceLogs().get( serviceConfiguration ).getProtocolURI();
260            File xmlFile = new File( xmlURI );
261            String xslURI = getProtocolURL().concat( JSPagesReference.getString( "OWSWatch.protocolXSLScript" ) );
262            File xslFile = new File( xslURI );
263            XSLTDocument sheet = new XSLTDocument();
264    
265            XMLFragment input = new XMLFragment();
266    
267            XMLFragment result = null;
268    
269            try {
270                input.load( xmlFile.toURL() );
271                sheet.load( xslFile.toURL() );
272                result = sheet.transform( input );
273            } catch ( Exception e ) {
274                gotoErrorPage( request, response, Messages.getMessage( "ERROR_LOADING_XML_FILE", "handleServiceProtocol()",
275                                                                       xmlFile.getAbsolutePath() ),
276                               Messages.getMessage( "MESSAGE_GOTO_MAIN" ),
277                               JSPagesReference.getString( "OWSWatch.owswatchMonitorList" ) );
278                return false;
279            }
280            String s = result.getAsString();
281    
282            request.setAttribute( "TABLE", s );
283            String idx = String.valueOf( serviceId );
284            request.setAttribute( "newWinProtocol", idx );
285            String next = null;
286            try {
287                next = JSPagesReference.getString( "OWSWatch.protocolJSP" );
288                getServletConfig().getServletContext().getRequestDispatcher( next ).forward( request, response );
289            } catch ( Exception e ) {
290                gotoErrorPage( request, response, Messages.getMessage( "ERROR_PAGE_NOT_FOUND", next ),
291                               Messages.getMessage( "MESSAGE_GOTO_MAIN" ),
292                               JSPagesReference.getString( "OWSWatch.owswatchMonitorList" ) );
293                return false;
294            }
295            return true;
296        }
297    
298        /**
299         * Logs the user out
300         *
301         * @return true if logout successfully, false otherwise
302         */
303        private boolean handleLogout( HttpServletRequest request, HttpServletResponse response ) {
304    
305            HttpSession session = request.getSession( true );
306            session.setAttribute( "isLoggedin", false );
307            session.removeAttribute( SESSIONID_KEY );
308    
309            String nextPage = JSPagesReference.getString( "OWSWatch.login" );
310            try {
311                response.sendRedirect( nextPage );
312            } catch ( Exception e ) {
313                gotoErrorPage( request, response, Messages.getMessage( "ERROR_PAGE_NOT_FOUND", nextPage ), null, null );
314                return false;
315            }
316    
317            return true;
318        }
319    
320        /**
321         * Verifies that this user is loggedin through comparing the session ID from the request paarameter with that saved
322         * in the session
323         *
324         * @param request
325         * @return true if the user is loggedin, false otherwise
326         */
327        protected boolean isLoggedIn( HttpServletRequest request ) {
328            HttpSession session = request.getSession( true );
329            String requestSession = request.getParameter( SESSIONID_KEY );
330            String sessionId = (String) session.getAttribute( SESSIONID_KEY );
331            if ( requestSession == null || sessionId == null || !requestSession.equals( sessionId ) ) {
332                return false;
333            }
334            return true;
335        }
336    
337        /**
338         * @return the Location of the protocol of this Service
339         */
340        public String getProtocolURL() {
341            String protDirePath = factory.getProtDirPath();
342            return protDirePath.endsWith( "/" ) ? protDirePath : protDirePath.concat( "/" );
343        }
344    }