001/*
002 *  Copyright 2014 Anyware Services
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 */
016package org.ametys.plugins.flipbook;
017
018import java.io.InputStream;
019
020import org.apache.commons.codec.digest.DigestUtils;
021import org.apache.tika.io.IOUtils;
022
023import org.ametys.plugins.explorer.resources.Resource;
024
025/**
026 * Implementation of a {@link AbstractConvertDocument2ImagesComponent} for a {@link Resource}
027 */
028public class ConvertResource2ImagesComponent extends AbstractConvertDocument2ImagesComponent
029{   
030    /** Avalon ROLE. */
031    public static final String ROLE = ConvertResource2ImagesComponent.class.getName();
032    
033    /**
034     * Put the file in cache
035     * @param resource the resource to cache
036     * @param siteName the name of the site
037     * @return The absolute cache path
038     * @throws Exception if an error occurs while caching the file
039     */
040    public String doCache(Resource resource, String siteName) throws Exception
041    {
042        // Ensure the base folder exists.
043        String cachePath = _getCacheDirectory(resource, siteName);
044        
045        InputStream is = null;
046        InputStream is2 = null;
047        try
048        {
049            is = resource.getInputStream();
050            String md5sum = DigestUtils.md5Hex(is);
051            
052            is2 = resource.getInputStream();
053            return cache(cachePath, md5sum, is2, resource.getName(), resource.getId(), resource.getMimeType());
054        }
055        finally
056        {
057            IOUtils.closeQuietly(is);
058            IOUtils.closeQuietly(is2);
059        }
060    }
061    
062    private String _getCacheDirectory(Resource resource, String siteName)
063    {
064        StringBuilder buff = new StringBuilder();
065        
066        String fullPath = resource.getPath();
067        if (fullPath.startsWith("/ametys:plugins/web-explorer/shared-resources"))
068        {
069            // Shared resources.
070            buff.append("/shared-resources");
071        }
072        else
073        {
074            // Non-shared resources.
075            buff.append("/");
076            buff.append(siteName);
077            buff.append("/resources");
078        }
079        
080        buff.append(resource.getResourcePath());
081        
082        return buff.toString();
083    }
084}