001    /**
002     * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portlet.documentlibrary.store;
016    
017    import com.liferay.portal.kernel.memory.DeleteFileFinalizeAction;
018    import com.liferay.portal.kernel.memory.FinalizeManager;
019    import com.liferay.portal.kernel.util.FileUtil;
020    
021    import java.io.File;
022    import java.io.FileInputStream;
023    import java.io.InputStream;
024    
025    import org.aopalliance.intercept.MethodInterceptor;
026    import org.aopalliance.intercept.MethodInvocation;
027    
028    /**
029     * @author Shuyang Zhou
030     */
031    public class TempFileMethodInterceptor implements MethodInterceptor {
032    
033            public Object invoke(MethodInvocation methodInvocation) throws Throwable {
034                    Object result = methodInvocation.proceed();
035    
036                    if (result instanceof InputStream) {
037                            InputStream inputStream = (InputStream)result;
038    
039                            File tempFile = FileUtil.createTempFile(inputStream);
040    
041                            result = new FileInputStream(tempFile);
042    
043                            FinalizeManager.register(
044                                    result,
045                                    new DeleteFileFinalizeAction(tempFile.getAbsolutePath()));
046                    }
047    
048                    return result;
049            }
050    
051    }