inti.ws.spring.resource.WebResource.java Source code

Java tutorial

Introduction

Here is the source code for inti.ws.spring.resource.WebResource.java

Source

/**
 * 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.util.DateFormatter;
import inti.ws.spring.resource.config.ConfigParserSettings;
import inti.ws.spring.resource.minify.Minifier;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.web.context.support.ServletContextResource;

public class WebResource {

    protected static final DateFormatter DATE_FORMATTER = new DateFormatter();
    private static final Logger LOGGER = LoggerFactory.getLogger(WebResource.class);
    protected static final ThreadLocal<MessageDigest> DIGESTS = new ThreadLocal<MessageDigest>() {

        @Override
        protected MessageDigest initialValue() {
            try {
                return MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException exception) {
                return null;
            }
        }

    };

    protected boolean minify;
    protected long lastModified = 0;
    protected Minifier minifier;
    protected String compressedFile;
    protected String messageDigest;
    protected String lastModifiedString;
    protected Resource resource;
    protected byte[] bytes;
    protected String route;

    public WebResource(ServletContext ctx, String location, String route, Minifier minifier, boolean minify)
            throws URISyntaxException, MalformedURLException {
        this.route = route;
        this.minifier = minifier;
        this.minify = minify;

        LOGGER.debug("WebResource - try to load {}", location);

        if (location != null) {
            if (location.startsWith("classpath:")) {
                resource = new ClassPathResource(location.substring(10));
            } else if (location.startsWith("/")) {
                resource = new ServletContextResource(ctx, location);
            } else {
                resource = new UrlResource(location);
            }
        }
    }

    public String getName() {
        return resource.getFilename();
    }

    public boolean hasChanged() throws IOException {
        return resource.lastModified() > lastModified;
    }

    public boolean updateIfNeeded() throws IOException, Exception {
        if (hasChanged()) {
            update();
            return true;
        }
        return false;
    }

    public void update() throws Exception {
        StringBuilder builder = new StringBuilder(32);
        MessageDigest digest = DIGESTS.get();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        InputStream inputStream = resource.getInputStream();

        try {
            lastModified = resource.lastModified();
            IOUtils.copyLarge(inputStream, outputStream);
            compressedFile = new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
        } finally {
            inputStream.close();
        }

        if (minify) {
            compressedFile = minifier.minify(compressedFile);
        }

        digest.reset();
        builder.append(Hex.encodeHexString(digest.digest(compressedFile.getBytes(StandardCharsets.UTF_8))));
        messageDigest = builder.toString();
        builder.delete(0, builder.length());

        DATE_FORMATTER.formatDate(lastModified, builder);
        lastModifiedString = builder.toString();
        bytes = null;
    }

    public long getLastModified() {
        return lastModified;
    }

    public String getLastModifiedString() {
        return lastModifiedString;
    }

    public String getMessageDigest() {
        return messageDigest;
    }

    public String getContent() {
        return compressedFile;
    }

    public void processResponse(HttpServletRequest request, HttpServletResponse response,
            ConfigParserSettings settings) {
    }

    public byte[] getByteContent(ConfigParserSettings settings) {
        if (bytes == null) {
            bytes = getContent().getBytes(Charset.forName(settings.getContentEncoding()));
        }
        return bytes;
    }

    public String getRoute() {
        return route;
    }

}