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.excalibur.source.Source; 022import org.apache.tika.io.IOUtils; 023 024import org.ametys.core.util.FilenameUtils; 025 026/** 027 * Implementation of a {@link AbstractConvertDocument2ImagesComponent} for an external resource 028 */ 029public class ConvertExternalResource2ImagesComponent extends AbstractConvertDocument2ImagesComponent 030{ 031 /** Avalon ROLE. */ 032 public static final String ROLE = ConvertExternalResource2ImagesComponent.class.getName(); 033 034 /** 035 * Put the file in cache 036 * @param resource the resource to cache 037 * @param path The resource path 038 * @param cacheDir The cache directory 039 * @param name The resource name 040 * @return The absolute cache path 041 * @throws Exception if an error occurs while caching the file 042 */ 043 public String doCache(Source resource, String path, String cacheDir, String name) throws Exception 044 { 045 // Ensure the base folder exists. 046 String cachePath = _getCacheDirectory(path, cacheDir); 047 048 InputStream is = null; 049 InputStream is2 = null; 050 try 051 { 052 is = resource.getInputStream(); 053 String md5sum = DigestUtils.md5Hex(is); 054 055 is2 = resource.getInputStream(); 056 return cache(cachePath, md5sum, is2, name, path, resource.getMimeType()); 057 } 058 finally 059 { 060 IOUtils.closeQuietly(is); 061 IOUtils.closeQuietly(is2); 062 } 063 } 064 065 private String _getCacheDirectory(String path, String cacheDir) 066 { 067 StringBuilder buff = new StringBuilder(); 068 069 // Non-shared resources. 070 buff.append("/"); 071 buff.append(cacheDir); 072 buff.append("/resources"); 073 buff.append(FilenameUtils.encodePath(path)); 074 075 return buff.toString(); 076 } 077}