Skip to main content
summaryrefslogtreecommitdiffstats
blob: cb722cc8301fd4e9f5e1aa5f4c0f2e1a39310d90 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
// ========================================================================
// Copyright (c) 2006-2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at 
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses. 
// ========================================================================

package org.eclipse.jetty.server.handler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.http.PathMap;
import org.eclipse.jetty.server.AsyncContinuation;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.HandlerContainer;
import org.eclipse.jetty.server.HttpConnection;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.util.LazyList;
import org.eclipse.jetty.util.log.Log;

/* ------------------------------------------------------------ */
/** ContextHandlerCollection.
 * 
 * This {@link org.eclipse.jetty.server.handler.HandlerCollection} is creates a 
 * {@link org.eclipse.jetty.http.servlet.PathMap} to it's contained handlers based
 * on the context path and virtual hosts of any contained {@link org.eclipse.jetty.server.handler.ContextHandler}s.
 * The contexts do not need to be directly contained, only children of the contained handlers.
 * Multiple contexts may have the same context path and they are called in order until one
 * handles the request.  
 * 
 * @org.apache.xbean.XBean element="contexts"
 */
public class ContextHandlerCollection extends HandlerCollection
{ 
    private volatile PathMap _contextMap;
    private Class<? extends ContextHandler> _contextClass = ContextHandler.class;
    
    public ContextHandlerCollection()
    {
        super(true);
    }
    
    /* ------------------------------------------------------------ */
    /**
     * Remap the context paths.
     */
    public void mapContexts()
    {
        PathMap contextMap = new PathMap();
        Handler[] branches = getHandlers();
        
        
        for (int b=0;branches!=null && b<branches.length;b++)
        {
            Handler[] handlers=null;
            
            if (branches[b] instanceof ContextHandler)
            {
                handlers = new Handler[]{ branches[b] };
            }
            else if (branches[b] instanceof HandlerContainer)
            {
                handlers = ((HandlerContainer)branches[b]).getChildHandlersByClass(ContextHandler.class);
            }
            else 
                continue;
            
            for (int i=0;i<handlers.length;i++)
            {
                ContextHandler handler=(ContextHandler)handlers[i];

                String contextPath=handler.getContextPath();

                if (contextPath==null || contextPath.indexOf(',')>=0 || contextPath.startsWith("*"))
                    throw new IllegalArgumentException ("Illegal context spec:"+contextPath);

                if(!contextPath.startsWith("/"))
                    contextPath='/'+contextPath;

                if (contextPath.length()>1)
                {
                    if (contextPath.endsWith("/"))
                        contextPath+="*";
                    else if (!contextPath.endsWith("/*"))
                        contextPath+="/*";
                }

                Object contexts=contextMap.get(contextPath);
                String[] vhosts=handler.getVirtualHosts();

                
                if (vhosts!=null && vhosts.length>0)
                {
                    Map hosts;

                    if (contexts instanceof Map)
                        hosts=(Map)contexts;
                    else
                    {
                        hosts=new HashMap(); 
                        hosts.put("*",contexts);
                        contextMap.put(contextPath, hosts);
                    }

                    for (int j=0;j<vhosts.length;j++)
                    {
                        String vhost=vhosts[j];
                        contexts=hosts.get(vhost);
                        contexts=LazyList.add(contexts,branches[b]);
                        hosts.put(vhost,contexts);
                    }
                }
                else if (contexts instanceof Map)
                {
                    Map hosts=(Map)contexts;
                    contexts=hosts.get("*");
                    contexts= LazyList.add(contexts, branches[b]);
                    hosts.put("*",contexts);
                }
                else
                {
                    contexts= LazyList.add(contexts, branches[b]);
                    contextMap.put(contextPath, contexts);
                }
            }
        }
        _contextMap=contextMap;

    }
    

    
    /* ------------------------------------------------------------ */
    /* 
     * @see org.eclipse.jetty.server.server.handler.HandlerCollection#setHandlers(org.eclipse.jetty.server.server.Handler[])
     */
    public void setHandlers(Handler[] handlers)
    {
        _contextMap=null;
        super.setHandlers(handlers);
        if (isStarted())
            mapContexts();
    }

    /* ------------------------------------------------------------ */
    protected void doStart() throws Exception
    {
        mapContexts();
        super.doStart();
    }
    

    /* ------------------------------------------------------------ */
    /* 
     * @see org.eclipse.jetty.server.server.Handler#handle(java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, int)
     */
    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
        Handler[] handlers = getHandlers();
        if (handlers==null || handlers.length==0)
	    return;
	
	AsyncContinuation async = baseRequest.getAsyncContinuation();
	if (async.isAsync())
	{
	    ContextHandler context=async.getContextHandler();
	    if (context!=null)
	    {
	        context.handle(target,baseRequest,request, response);
	        return;
	    }
	}
	
	// data structure which maps a request to a context; first-best match wins
	// { context path => 
	//     { virtual host => context } 
	// }
	PathMap map = _contextMap;
	if (map!=null && target!=null && target.startsWith("/"))
	{
	    // first, get all contexts matched by context path
	    Object contexts = map.getLazyMatches(target);

            for (int i=0; i<LazyList.size(contexts); i++)
            {
                // then, match against the virtualhost of each context
                Map.Entry entry = (Map.Entry)LazyList.get(contexts, i);
                Object list = entry.getValue();

                if (list instanceof Map)
                {
                    Map hosts = (Map)list;
                    String host = normalizeHostname(request.getServerName());
           
                    // explicitly-defined virtual hosts, most specific
                    list=hosts.get(host);
                    for (int j=0; j<LazyList.size(list); j++)
                    {
                        Handler handler = (Handler)LazyList.get(list,j);
                        handler.handle(target,baseRequest, request, response);
                        if (baseRequest.isHandled())
                            return;
                    }
                    
                    // wildcard for one level of names 
                    list=hosts.get("*."+host.substring(host.indexOf(".")+1));
                    for (int j=0; j<LazyList.size(list); j++)
                    {
                        Handler handler = (Handler)LazyList.get(list,j);
                        handler.handle(target,baseRequest, request, response);
                        if (baseRequest.isHandled())
                            return;
                    }
                    
                    // no virtualhosts defined for the context, least specific
                    // will handle any request that does not match to a specific virtual host above
                    list=hosts.get("*");
                    for (int j=0; j<LazyList.size(list); j++)
                    {
                        Handler handler = (Handler)LazyList.get(list,j);
                        handler.handle(target,baseRequest, request, response);
                        if (baseRequest.isHandled())
                            return;
                    }
                }
                else
                {
                    for (int j=0; j<LazyList.size(list); j++)
                    {
                        Handler handler = (Handler)LazyList.get(list,j);
                        handler.handle(target,baseRequest, request, response);
                        if (baseRequest.isHandled())
                            return;
                    }
                }
	    }
	}
	else
	{
            // This may not work in all circumstances... but then I think it should never be called
	    for (int i=0;i<handlers.length;i++)
	    {
		handlers[i].handle(target,baseRequest, request, response);
		if ( baseRequest.isHandled())
		    return;
	    }
	}
    }
    
    
    /* ------------------------------------------------------------ */
    /** Add a context handler.
     * @param contextPath  The context path to add
     * @return
     * @throws IllegalAccessException 
     * @throws InstantiationException 
     */
    public ContextHandler addContext(String contextPath,String resourceBase) 
    {
        try
        {
            ContextHandler context = _contextClass.newInstance();
            context.setContextPath(contextPath);
            context.setResourceBase(resourceBase);
            addHandler(context);
            return context;
        }
        catch (Exception e)
        {
            Log.warn(e);
            throw new Error(e);
        }
    }



    /* ------------------------------------------------------------ */
    /**
     * @return The class to use to add new Contexts
     */
    public Class getContextClass()
    {
        return _contextClass;
    }


    /* ------------------------------------------------------------ */
    /**
     * @param contextClass The class to use to add new Contexts
     */
    public void setContextClass(Class contextClass)
    {
        if (contextClass ==null || !(ContextHandler.class.isAssignableFrom(contextClass)))
            throw new IllegalArgumentException();
        _contextClass = contextClass;
    }
    
    /* ------------------------------------------------------------ */
    private String normalizeHostname( String host )
    {
        if ( host == null )
            return null;
        
        if ( host.endsWith( "." ) )
            return host.substring( 0, host.length() -1);
      
        return host;
    }
    
}

Back to the top