001    /**
002     * Copyright (c) 2000-2013 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            @Override
034            public Object invoke(MethodInvocation methodInvocation) throws Throwable {
035                    Object result = methodInvocation.proceed();
036    
037                    if (result instanceof InputStream) {
038                            InputStream inputStream = (InputStream)result;
039    
040                            File tempFile = FileUtil.createTempFile(inputStream);
041    
042                            result = new FileInputStream(tempFile);
043    
044                            FinalizeManager.register(
045                                    result,
046                                    new DeleteFileFinalizeAction(tempFile.getAbsolutePath()));
047                    }
048    
049                    return result;
050            }
051    
052    }