001// Copyright 2013 The Apache Software Foundation
002//
003// Licensed under the Apache License, Version 2.0 (the "License");
004// you may not use this file except in compliance with the License.
005// You may obtain a copy of the License at
006//
007// http://www.apache.org/licenses/LICENSE-2.0
008//
009// Unless required by applicable law or agreed to in writing, software
010// distributed under the License is distributed on an "AS IS" BASIS,
011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012// See the License for the specific language governing permissions and
013// limitations under the License.
014
015package org.apache.tapestry5.internal.webresources;
016
017import org.apache.tapestry5.ioc.Resource;
018
019import java.io.IOException;
020import java.io.InputStream;
021import java.util.zip.Adler32;
022
023/**
024 * @since 5.4
025 */
026public class ResourceTransformUtils
027{
028    private static final double NANOS_TO_MILLIS = 1.0d / 1000000.0d;
029
030    public static double nanosToMillis(long nanos)
031    {
032        return ((double) nanos) * NANOS_TO_MILLIS;
033    }
034
035    public static long toChecksum(Resource resource)
036    {
037        Adler32 checksum = new Adler32();
038
039        byte[] buffer = new byte[1024];
040
041        InputStream is = null;
042
043        try
044        {
045            is = resource.openStream();
046
047            while (true)
048            {
049                int length = is.read(buffer);
050
051                if (length < 0)
052                {
053                    break;
054                }
055
056                checksum.update(buffer, 0, length);
057            }
058
059            is.close();
060
061            // Reduces it down to just 32 bits which we express in hex.'
062            return checksum.getValue();
063        } catch (IOException ex)
064        {
065            throw new RuntimeException(ex);
066        }
067    }
068}