001/*
002 * (C) Copyright 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Nuxeo - initial API and implementation
018 *
019 */
020package org.nuxeo.ecm.core.convert.cache;
021
022import java.io.File;
023import java.io.IOException;
024import java.util.Date;
025
026import org.nuxeo.ecm.core.api.blobholder.BlobHolder;
027import org.nuxeo.ecm.core.convert.api.ConversionService;
028
029/**
030 * Represents an Entry in the {@link ConversionService} cache system.
031 * <p>
032 * Manages timestamp and persistence.
033 *
034 * @author tiry
035 */
036public class ConversionCacheEntry {
037
038    protected Date lastAccessTime;
039
040    protected BlobHolder bh;
041
042    protected boolean persisted = false;
043
044    protected String persistPath;
045
046    protected long sizeInKB = 0;
047
048    public ConversionCacheEntry(BlobHolder bh) {
049        this.bh = bh;
050        updateAccessTime();
051    }
052
053    protected void updateAccessTime() {
054        lastAccessTime = new Date();
055    }
056
057    public boolean persist(String basePath) throws IOException {
058        if (bh instanceof CachableBlobHolder) {
059            CachableBlobHolder cbh = (CachableBlobHolder) bh;
060            persistPath = cbh.persist(basePath);
061            if (persistPath != null) {
062                sizeInKB = new File(persistPath).length() / 1024;
063                persisted = true;
064            }
065        }
066        bh = null;
067        return persisted;
068    }
069
070    public void remove() {
071        if (persisted && persistPath != null) {
072            new File(persistPath).delete();
073        }
074    }
075
076    public BlobHolder restore() {
077        updateAccessTime();
078        if (persisted && persistPath != null) {
079            try {
080                CachableBlobHolder holder = new SimpleCachableBlobHolder();
081                holder.load(persistPath);
082                return holder;
083            } catch (IOException e) {
084                throw new RuntimeException(e);
085            }
086        } else {
087            return null;
088        }
089    }
090
091    public long getDiskSpaceUsageInKB() {
092        return sizeInKB;
093    }
094
095    public Date getLastAccessedTime() {
096        return lastAccessTime;
097    }
098
099}