Line data Source code
1 : // Copyright (C) 2012 The Android Open Source Project 2 : // 3 : // Licensed under the Apache License, Version 2.0 (the "License"); 4 : // you may not use this file except in compliance with the License. 5 : // You may obtain a copy of the License at 6 : // 7 : // http://www.apache.org/licenses/LICENSE-2.0 8 : // 9 : // Unless required by applicable law or agreed to in writing, software 10 : // distributed under the License is distributed on an "AS IS" BASIS, 11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 : // See the License for the specific language governing permissions and 13 : // limitations under the License. 14 : 15 : package com.google.gerrit.httpd.resources; 16 : 17 : import com.google.common.net.HttpHeaders; 18 : import com.google.gerrit.common.Nullable; 19 : import java.io.IOException; 20 : import javax.servlet.http.HttpServletRequest; 21 : import javax.servlet.http.HttpServletResponse; 22 : 23 : public final class SmallResource extends Resource { 24 : private static final long serialVersionUID = 1L; 25 : private final byte[] data; 26 : private String contentType; 27 : private String characterEncoding; 28 : private long lastModified; 29 : 30 0 : public SmallResource(byte[] data) { 31 0 : this.data = data; 32 0 : } 33 : 34 : public SmallResource setLastModified(long when) { 35 0 : this.lastModified = when; 36 0 : return this; 37 : } 38 : 39 : public SmallResource setContentType(String contentType) { 40 0 : this.contentType = contentType; 41 0 : return this; 42 : } 43 : 44 : public SmallResource setCharacterEncoding(@Nullable String enc) { 45 0 : this.characterEncoding = enc; 46 0 : return this; 47 : } 48 : 49 : @Override 50 : public int weigh() { 51 0 : return contentType.length() * 2 + data.length; 52 : } 53 : 54 : @Override 55 : public void send(HttpServletRequest req, HttpServletResponse res) throws IOException { 56 0 : if (0 < lastModified) { 57 0 : long ifModifiedSince = req.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE); 58 0 : if (ifModifiedSince > 0 && ifModifiedSince == lastModified) { 59 0 : res.setStatus(HttpServletResponse.SC_NOT_MODIFIED); 60 0 : return; 61 : } 62 0 : res.setDateHeader("Last-Modified", lastModified); 63 : } 64 0 : res.setContentType(contentType); 65 0 : if (characterEncoding != null) { 66 0 : res.setCharacterEncoding(characterEncoding); 67 : } 68 0 : res.setContentLength(data.length); 69 0 : res.getOutputStream().write(data); 70 0 : } 71 : 72 : @Override 73 : public boolean isUnchanged(long lastModified) { 74 0 : return this.lastModified == lastModified; 75 : } 76 : }