001 /**
002 * Copyright (C) 2009-2011 the original author or authors.
003 * See the notice.md file distributed with this work for additional
004 * information regarding copyright ownership.
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License");
007 * you may not use this file except in compliance with the License.
008 * You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019 package org.fusesource.restygwt.client.callback;
020
021 import org.fusesource.restygwt.client.Method;
022 import org.fusesource.restygwt.client.cache.CacheKey;
023 import org.fusesource.restygwt.client.cache.QueueableCacheStorage;
024 import org.fusesource.restygwt.client.cache.UrlCacheKey;
025 import org.fusesource.restygwt.client.dispatcher.RestfulCachingDispatcherFilter;
026
027 import com.google.gwt.http.client.RequestBuilder;
028 import com.google.gwt.http.client.Response;
029
030 /**
031 * see {@link RestfulCachingDispatcherFilter}
032 */
033 public class RestfulCachingCallbackFilter extends CachingCallbackFilter {
034
035 public RestfulCachingCallbackFilter(QueueableCacheStorage cache) {
036 super(cache);
037 }
038
039 @Override
040 protected CacheKey cacheKey(RequestBuilder builder) {
041 return new UrlCacheKey(builder);
042 }
043
044 @Override
045 protected void cacheResult(Method method, Response response) {
046 final CacheKey cacheKey;
047 if (response.getStatusCode() == Response.SC_CREATED && response.getHeader("Location") != null){
048 // TODO very fragile way of getting the URL
049 final String uri;
050 if(response.getHeader("Location").startsWith("http")){
051 uri = response.getHeader("Location");
052 }
053 else {
054 uri = method.builder.getUrl().replaceFirst("/[^/]*$", "") + response.getHeader("Location");
055 }
056 cacheKey = new UrlCacheKey(uri);
057 }
058 else {
059 cacheKey = cacheKey(method.builder);
060 }
061
062 if (RequestBuilder.DELETE.toString().equalsIgnoreCase(
063 method.builder.getHTTPMethod()) ||
064 // in case of a conflict the next GET request needs to
065 // go remote !!
066 response.getStatusCode() == Response.SC_CONFLICT) {
067 cache.remove(cacheKey);
068 } else {
069 cache.putResult(cacheKey, response);
070 }
071 }
072 }