001 /*
002 * Apache License
003 * Version 2.0, January 2004
004 * http://www.apache.org/licenses/
005 *
006 * Copyright 2008 by chenillekit.org
007 *
008 * Licensed under the Apache License, Version 2.0 (the "License");
009 * you may not use this file except in compliance with the License.
010 * You may obtain a copy of the License at
011 *
012 * http://www.apache.org/licenses/LICENSE-2.0
013 */
014
015 package org.chenillekit.tapestry.core.services.impl;
016
017 import java.io.IOException;
018 import javax.servlet.http.HttpServletResponse;
019
020 import org.apache.tapestry5.internal.services.ResourceStreamer;
021 import org.apache.tapestry5.ioc.Resource;
022 import org.apache.tapestry5.services.Dispatcher;
023 import org.apache.tapestry5.services.Request;
024 import org.apache.tapestry5.services.Response;
025
026 import org.chenillekit.core.resources.URIResource;
027 import org.chenillekit.tapestry.core.ChenilleKitCoreConstants;
028 import org.chenillekit.tapestry.core.services.URIAssetAliasManager;
029
030 /**
031 * @version $Id: URIDispatcher.java 594 2009-12-05 15:17:26Z mlusetti $
032 */
033 public class URIDispatcher implements Dispatcher
034 {
035 private final ResourceStreamer streamer;
036
037 private final URIAssetAliasManager aliasManager;
038
039 public URIDispatcher(ResourceStreamer streamer, URIAssetAliasManager aliasManager)
040 {
041 this.streamer = streamer;
042 this.aliasManager = aliasManager;
043 }
044
045 /**
046 * Analyzes the incoming request and performs an appropriate operation for each.
047 *
048 * @return true if a response was delivered, false if the servlet container should be allowed to handle the request
049 */
050 public boolean dispatch(Request request, Response response) throws IOException
051 {
052 String path = request.getPath();
053
054 // Remember that the request path does not include the context path, so we can simply start
055 // looking for the asset path prefix right off the bat.
056 if (!path.startsWith(ChenilleKitCoreConstants.URI_PATH_PREFIX)) return false;
057
058 String resourcePath = aliasManager.toResourcePath(path);
059
060 Resource resource = new URIResource(resourcePath);
061
062 if (!resource.exists())
063 {
064 response.sendError(HttpServletResponse.SC_NOT_FOUND, String.format("asset '%s' doesn exists!", resource));
065 return true;
066 }
067
068 streamer.streamResource(resource);
069
070 return true;
071 }
072 }