001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     Nuxeo - initial API and implementation
011 *
012 */
013package org.nuxeo.ecm.core.convert.cache;
014
015import java.io.File;
016import java.io.IOException;
017import java.util.Date;
018
019import org.nuxeo.ecm.core.api.blobholder.BlobHolder;
020import org.nuxeo.ecm.core.convert.api.ConversionService;
021
022/**
023 * Represents an Entry in the {@link ConversionService} cache system.
024 * <p>
025 * Manages timestamp and persistence.
026 *
027 * @author tiry
028 */
029public class ConversionCacheEntry {
030
031    protected Date lastAccessTime;
032
033    protected BlobHolder bh;
034
035    protected boolean persisted = false;
036
037    protected String persistPath;
038
039    protected long sizeInKB = 0;
040
041    public ConversionCacheEntry(BlobHolder bh) {
042        this.bh = bh;
043        updateAccessTime();
044    }
045
046    protected void updateAccessTime() {
047        lastAccessTime = new Date();
048    }
049
050    public boolean persist(String basePath) throws IOException {
051        if (bh instanceof CachableBlobHolder) {
052            CachableBlobHolder cbh = (CachableBlobHolder) bh;
053            persistPath = cbh.persist(basePath);
054            if (persistPath != null) {
055                sizeInKB = new File(persistPath).length() / 1024;
056                persisted = true;
057            }
058        }
059        bh = null;
060        return persisted;
061    }
062
063    public void remove() {
064        if (persisted && persistPath != null) {
065            new File(persistPath).delete();
066        }
067    }
068
069    public BlobHolder restore() {
070        updateAccessTime();
071        if (persisted && persistPath != null) {
072            try {
073                CachableBlobHolder holder = new SimpleCachableBlobHolder();
074                holder.load(persistPath);
075                return holder;
076            } catch (IOException e) {
077                throw new RuntimeException(e);
078            }
079        } else {
080            return null;
081        }
082    }
083
084    public long getDiskSpaceUsageInKB() {
085        return sizeInKB;
086    }
087
088    public Date getLastAccessedTime() {
089        return lastAccessTime;
090    }
091
092}