001/** 002 * 003 * Copyright (c) 2014, the Railo Company Ltd. All rights reserved. 004 * 005 * This library is free software; you can redistribute it and/or 006 * modify it under the terms of the GNU Lesser General Public 007 * License as published by the Free Software Foundation; either 008 * version 2.1 of the License, or (at your option) any later version. 009 * 010 * This library is distributed in the hope that it will be useful, 011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 013 * Lesser General Public License for more details. 014 * 015 * You should have received a copy of the GNU Lesser General Public 016 * License along with this library. If not, see <http://www.gnu.org/licenses/>. 017 * 018 **/ 019package lucee.commons.io; 020 021import java.io.IOException; 022import java.io.InputStream; 023 024import lucee.commons.io.res.Resource; 025import lucee.commons.lang.StringUtil; 026 027public class FileRotation { 028 public static void checkFile(Resource res, long maxFileSize, int maxFiles, byte[] header) throws IOException { 029 boolean writeHeader=false; 030 // create file 031 if(!res.exists()) { 032 res.createFile(true); 033 writeHeader=true; 034 } 035 else if(res.length()==0) { 036 writeHeader=true; 037 } 038 039 040 // create new file 041 else if(res.length()>maxFileSize) { 042 Resource parent = res.getParentResource(); 043 String name = res.getName(); 044 int lenMaxFileSize=(""+maxFiles).length(); 045 for(int i=maxFiles;i>0;i--) { 046 047 Resource to=parent.getRealResource(name+"."+StringUtil.addZeros(i, lenMaxFileSize)+".bak"); 048 Resource from=parent.getRealResource(name+"."+StringUtil.addZeros(i-1,lenMaxFileSize)+".bak"); 049 if(from.exists()) { 050 if(to.exists())to.delete(); 051 from.renameTo(to); 052 } 053 } 054 res.renameTo(parent.getRealResource(name+"."+StringUtil.addZeros(1,lenMaxFileSize)+".bak")); 055 res=parent.getRealResource(name);//new File(parent,name); 056 res.createNewFile(); 057 writeHeader=true; 058 } 059 else if(header!=null && header.length>0) { 060 byte[] buffer = new byte[header.length]; 061 int len; 062 InputStream in = null; 063 try{ 064 in = res.getInputStream(); 065 boolean headerOK = true; 066 len = in.read(buffer); 067 if(len==header.length){ 068 for(int i=0;i<header.length;i++) { 069 if(header[i]!=buffer[i]){ 070 headerOK=false; 071 break; 072 } 073 } 074 } 075 else headerOK=false; 076 if(!headerOK)writeHeader=true; 077 } 078 finally { 079 IOUtil.closeEL(in); 080 } 081 } 082 083 084 if(writeHeader) { 085 if(header==null)header=new byte[0]; 086 IOUtil.write(res, header,false); 087 088 } 089 } 090}