001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.servlet.filters.etag;
016    
017    import com.liferay.portal.kernel.servlet.HttpHeaders;
018    import com.liferay.portal.kernel.util.StringPool;
019    import com.liferay.portal.kernel.util.StringUtil;
020    
021    import java.nio.ByteBuffer;
022    
023    import javax.servlet.http.HttpServletRequest;
024    import javax.servlet.http.HttpServletResponse;
025    
026    /**
027     * @author Brian Wing Shun Chan
028     * @author Shuyang Zhou
029     */
030    public class ETagUtil {
031    
032            public static boolean processETag(
033                    HttpServletRequest request, HttpServletResponse response,
034                    ByteBuffer byteBuffer) {
035    
036                    if (response.isCommitted()) {
037                            return false;
038                    }
039    
040                    int hashCode = _hashCode(
041                            byteBuffer.array(), byteBuffer.position(), byteBuffer.limit());
042    
043                    String eTag = StringPool.QUOTE.concat(
044                            StringUtil.toHexString(hashCode)).concat(StringPool.QUOTE);
045    
046                    response.setHeader(HttpHeaders.ETAG, eTag);
047    
048                    String ifNoneMatch = request.getHeader(HttpHeaders.IF_NONE_MATCH);
049    
050                    if (eTag.equals(ifNoneMatch)) {
051                            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
052                            response.setContentLength(0);
053    
054                            return true;
055                    }
056                    else {
057                            return false;
058                    }
059            }
060    
061            private static int _hashCode(byte[] data, int offset, int length) {
062                    int hashCode = 0;
063    
064                    for (int i = 0; i < length; i++) {
065                            hashCode = 31 * hashCode + data[offset++];
066                    }
067    
068                    return hashCode;
069            }
070    
071    }