Java tutorial
/** * Copyright 2012 the project-owners * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package inti.ws.spring.resource; import inti.ws.spring.resource.config.ConfigParserSettings; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; import javax.activation.MimetypesFileTypeMap; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.codec.binary.Hex; import org.apache.commons.io.IOUtils; import org.apache.http.HttpHeaders; /** * The ByteResource mainly represents files of any kind. ByteReresources are not minified at all and will never change * it's content. */ public class ByteWebResource extends WebResource { /** * The content. */ protected byte[] bytes; /** * The contentType / MIME-Type. */ protected String contentType; public ByteWebResource(ServletContext ctx, String location, String route) throws Exception { super(ctx, location, route, null, false); contentType = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(location); update(); } /** * Always returns false. */ @Override public boolean hasChanged() throws IOException { return false; } /** * Always returns false. */ @Override public boolean updateIfNeeded() throws IOException, Exception { return false; } /** * Reads the file and stores it's content. */ @Override public void update() throws Exception { StringBuilder builder = new StringBuilder(32); MessageDigest digest = DIGESTS.get(); InputStream inputStream = resource.getInputStream(); try { lastModified = resource.lastModified(); bytes = IOUtils.toByteArray(inputStream); } finally { inputStream.close(); } digest.reset(); builder.append(Hex.encodeHexString(digest.digest(bytes))); messageDigest = builder.toString(); builder.delete(0, builder.length()); DATE_FORMATTER.formatDate(lastModified, builder); lastModifiedString = builder.toString(); } /** * Sets the MIME-Type as contentType. */ @Override public void processResponse(HttpServletRequest request, HttpServletResponse response, ConfigParserSettings settings) { super.processResponse(request, response, settings); if (contentType != null) { response.setHeader(HttpHeaders.CONTENT_TYPE, contentType); } } @Override public byte[] getByteContent(ConfigParserSettings settings) { return bytes; } }