001/** 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.camel.component.file; 018 019import java.io.File; 020import java.util.Map; 021import java.util.concurrent.locks.Lock; 022import java.util.concurrent.locks.ReentrantLock; 023 024import org.apache.camel.Exchange; 025import org.apache.camel.Expression; 026import org.apache.camel.impl.DefaultExchange; 027import org.apache.camel.impl.DefaultProducer; 028import org.apache.camel.util.FileUtil; 029import org.apache.camel.util.LRUCacheFactory; 030import org.apache.camel.util.ObjectHelper; 031import org.apache.camel.util.ServiceHelper; 032import org.apache.camel.util.StringHelper; 033import org.slf4j.Logger; 034import org.slf4j.LoggerFactory; 035 036/** 037 * Generic file producer 038 */ 039public class GenericFileProducer<T> extends DefaultProducer { 040 protected final Logger log = LoggerFactory.getLogger(getClass()); 041 protected final GenericFileEndpoint<T> endpoint; 042 protected GenericFileOperations<T> operations; 043 // assume writing to 100 different files concurrently at most for the same file producer 044 private final Map<String, Lock> locks = LRUCacheFactory.newLRUCache(100); 045 046 protected GenericFileProducer(GenericFileEndpoint<T> endpoint, GenericFileOperations<T> operations) { 047 super(endpoint); 048 this.endpoint = endpoint; 049 this.operations = operations; 050 } 051 052 public String getFileSeparator() { 053 return File.separator; 054 } 055 056 public String normalizePath(String name) { 057 return FileUtil.normalizePath(name); 058 } 059 060 public void process(Exchange exchange) throws Exception { 061 // store any existing file header which we want to keep and propagate 062 final String existing = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class); 063 064 // create the target file name 065 String target = createFileName(exchange); 066 067 // use lock for same file name to avoid concurrent writes to the same file 068 // for example when you concurrently append to the same file 069 Lock lock; 070 synchronized (locks) { 071 lock = locks.get(target); 072 if (lock == null) { 073 lock = new ReentrantLock(); 074 locks.put(target, lock); 075 } 076 } 077 078 lock.lock(); 079 try { 080 processExchange(exchange, target); 081 } finally { 082 // do not remove as the locks cache has an upper bound 083 // this ensure the locks is appropriate reused 084 lock.unlock(); 085 // and remove the write file name header as we only want to use it once (by design) 086 exchange.getIn().removeHeader(Exchange.OVERRULE_FILE_NAME); 087 // and restore existing file name 088 exchange.getIn().setHeader(Exchange.FILE_NAME, existing); 089 } 090 } 091 092 /** 093 * Sets the operations to be used. 094 * <p/> 095 * Can be used to set a fresh operations in case of recovery attempts 096 * 097 * @param operations the operations 098 */ 099 public void setOperations(GenericFileOperations<T> operations) { 100 this.operations = operations; 101 } 102 103 /** 104 * Perform the work to process the fileExchange 105 * 106 * @param exchange fileExchange 107 * @param target the target filename 108 * @throws Exception is thrown if some error 109 */ 110 protected void processExchange(Exchange exchange, String target) throws Exception { 111 log.trace("Processing file: {} for exchange: {}", target, exchange); 112 113 try { 114 preWriteCheck(exchange); 115 116 // should we write to a temporary name and then afterwards rename to real target 117 boolean writeAsTempAndRename = ObjectHelper.isNotEmpty(endpoint.getTempFileName()); 118 String tempTarget = null; 119 // remember if target exists to avoid checking twice 120 Boolean targetExists; 121 if (writeAsTempAndRename) { 122 // compute temporary name with the temp prefix 123 tempTarget = createTempFileName(exchange, target); 124 125 log.trace("Writing using tempNameFile: {}", tempTarget); 126 127 //if we should eager delete target file before deploying temporary file 128 if (endpoint.getFileExist() != GenericFileExist.TryRename && endpoint.isEagerDeleteTargetFile()) { 129 130 // cater for file exists option on the real target as 131 // the file operations code will work on the temp file 132 133 // if an existing file already exists what should we do? 134 targetExists = operations.existsFile(target); 135 if (targetExists) { 136 137 log.trace("EagerDeleteTargetFile, target exists"); 138 139 if (endpoint.getFileExist() == GenericFileExist.Ignore) { 140 // ignore but indicate that the file was written 141 log.trace("An existing file already exists: {}. Ignore and do not override it.", target); 142 return; 143 } else if (endpoint.getFileExist() == GenericFileExist.Fail) { 144 throw new GenericFileOperationFailedException("File already exist: " + target + ". Cannot write new file."); 145 } else if (endpoint.getFileExist() == GenericFileExist.Move) { 146 // move any existing file first 147 this.endpoint.getMoveExistingFileStrategy().moveExistingFile(endpoint, operations, target); 148 } else if (endpoint.isEagerDeleteTargetFile() && endpoint.getFileExist() == GenericFileExist.Override) { 149 // we override the target so we do this by deleting it so the temp file can be renamed later 150 // with success as the existing target file have been deleted 151 log.trace("Eagerly deleting existing file: {}", target); 152 if (!operations.deleteFile(target)) { 153 throw new GenericFileOperationFailedException("Cannot delete file: " + target); 154 } 155 } 156 } 157 } 158 159 // delete any pre existing temp file 160 if (endpoint.getFileExist() != GenericFileExist.TryRename && operations.existsFile(tempTarget)) { 161 log.trace("Deleting existing temp file: {}", tempTarget); 162 if (!operations.deleteFile(tempTarget)) { 163 throw new GenericFileOperationFailedException("Cannot delete file: " + tempTarget); 164 } 165 } 166 } 167 168 // write/upload the file 169 writeFile(exchange, tempTarget != null ? tempTarget : target); 170 171 // if we did write to a temporary name then rename it to the real 172 // name after we have written the file 173 if (tempTarget != null) { 174 // if we did not eager delete the target file 175 if (endpoint.getFileExist() != GenericFileExist.TryRename && !endpoint.isEagerDeleteTargetFile()) { 176 177 // if an existing file already exists what should we do? 178 targetExists = operations.existsFile(target); 179 if (targetExists) { 180 181 log.trace("Not using EagerDeleteTargetFile, target exists"); 182 183 if (endpoint.getFileExist() == GenericFileExist.Ignore) { 184 // ignore but indicate that the file was written 185 log.trace("An existing file already exists: {}. Ignore and do not override it.", target); 186 return; 187 } else if (endpoint.getFileExist() == GenericFileExist.Fail) { 188 throw new GenericFileOperationFailedException("File already exist: " + target + ". Cannot write new file."); 189 } else if (endpoint.getFileExist() == GenericFileExist.Override) { 190 // we override the target so we do this by deleting it so the temp file can be renamed later 191 // with success as the existing target file have been deleted 192 log.trace("Deleting existing file: {}", target); 193 if (!operations.deleteFile(target)) { 194 throw new GenericFileOperationFailedException("Cannot delete file: " + target); 195 } 196 } 197 } 198 } 199 200 // now we are ready to rename the temp file to the target file 201 log.trace("Renaming file: [{}] to: [{}]", tempTarget, target); 202 boolean renamed = operations.renameFile(tempTarget, target); 203 if (!renamed) { 204 throw new GenericFileOperationFailedException("Cannot rename file from: " + tempTarget + " to: " + target); 205 } 206 } 207 208 // any done file to write? 209 if (endpoint.getDoneFileName() != null) { 210 String doneFileName = endpoint.createDoneFileName(target); 211 StringHelper.notEmpty(doneFileName, "doneFileName", endpoint); 212 213 // create empty exchange with empty body to write as the done file 214 Exchange empty = new DefaultExchange(exchange); 215 empty.getIn().setBody(""); 216 217 log.trace("Writing done file: [{}]", doneFileName); 218 // delete any existing done file 219 if (operations.existsFile(doneFileName)) { 220 if (!operations.deleteFile(doneFileName)) { 221 throw new GenericFileOperationFailedException("Cannot delete existing done file: " + doneFileName); 222 } 223 } 224 writeFile(empty, doneFileName); 225 } 226 227 // let's store the name we really used in the header, so end-users 228 // can retrieve it 229 exchange.getIn().setHeader(Exchange.FILE_NAME_PRODUCED, target); 230 } catch (Exception e) { 231 handleFailedWrite(exchange, e); 232 } 233 234 postWriteCheck(exchange); 235 } 236 237 /** 238 * If we fail writing out a file, we will call this method. This hook is 239 * provided to disconnect from servers or clean up files we created (if needed). 240 */ 241 public void handleFailedWrite(Exchange exchange, Exception exception) throws Exception { 242 throw exception; 243 } 244 245 /** 246 * Perform any actions that need to occur before we write such as connecting to an FTP server etc. 247 */ 248 public void preWriteCheck(Exchange exchange) throws Exception { 249 // nothing needed to check 250 } 251 252 /** 253 * Perform any actions that need to occur after we are done such as disconnecting. 254 */ 255 public void postWriteCheck(Exchange exchange) { 256 // nothing needed to check 257 } 258 259 public void writeFile(Exchange exchange, String fileName) throws GenericFileOperationFailedException { 260 // build directory if auto create is enabled 261 if (endpoint.isAutoCreate()) { 262 // we must normalize it (to avoid having both \ and / in the name which confuses java.io.File) 263 String name = FileUtil.normalizePath(fileName); 264 265 // use java.io.File to compute the file path 266 File file = new File(name); 267 String directory = file.getParent(); 268 boolean absolute = FileUtil.isAbsolute(file); 269 if (directory != null) { 270 if (!operations.buildDirectory(directory, absolute)) { 271 log.debug("Cannot build directory [{}] (could be because of denied permissions)", directory); 272 } 273 } 274 } 275 276 // upload 277 if (log.isTraceEnabled()) { 278 log.trace("About to write [{}] to [{}] from exchange [{}]", fileName, getEndpoint(), exchange); 279 } 280 281 boolean success = operations.storeFile(fileName, exchange, -1); 282 if (!success) { 283 throw new GenericFileOperationFailedException("Error writing file [" + fileName + "]"); 284 } 285 log.debug("Wrote [{}] to [{}]", fileName, getEndpoint()); 286 } 287 288 public String createFileName(Exchange exchange) { 289 String answer; 290 291 // overrule takes precedence 292 Object value; 293 294 Object overrule = exchange.getIn().getHeader(Exchange.OVERRULE_FILE_NAME); 295 if (overrule != null) { 296 if (overrule instanceof Expression) { 297 value = overrule; 298 } else { 299 value = exchange.getContext().getTypeConverter().convertTo(String.class, exchange, overrule); 300 } 301 } else { 302 value = exchange.getIn().getHeader(Exchange.FILE_NAME); 303 } 304 305 // if we have an overrule then override the existing header to use the overrule computed name from this point forward 306 if (overrule != null) { 307 exchange.getIn().setHeader(Exchange.FILE_NAME, value); 308 } 309 310 if (value instanceof String && StringHelper.hasStartToken((String) value, "simple")) { 311 log.warn("Simple expression: {} detected in header: {} of type String. This feature has been removed (see CAMEL-6748).", value, Exchange.FILE_NAME); 312 } 313 314 // expression support 315 Expression expression = endpoint.getFileName(); 316 if (value instanceof Expression) { 317 expression = (Expression) value; 318 } 319 320 // evaluate the name as a String from the value 321 String name; 322 if (expression != null) { 323 log.trace("Filename evaluated as expression: {}", expression); 324 name = expression.evaluate(exchange, String.class); 325 } else { 326 name = exchange.getContext().getTypeConverter().convertTo(String.class, exchange, value); 327 } 328 329 // flatten name 330 if (name != null && endpoint.isFlatten()) { 331 // check for both windows and unix separators 332 int pos = Math.max(name.lastIndexOf("/"), name.lastIndexOf("\\")); 333 if (pos != -1) { 334 name = name.substring(pos + 1); 335 } 336 } 337 338 // compute path by adding endpoint starting directory 339 String endpointPath = endpoint.getConfiguration().getDirectory(); 340 String baseDir = ""; 341 if (endpointPath.length() > 0) { 342 // Its a directory so we should use it as a base path for the filename 343 // If the path isn't empty, we need to add a trailing / if it isn't already there 344 baseDir = endpointPath; 345 boolean trailingSlash = endpointPath.endsWith("/") || endpointPath.endsWith("\\"); 346 if (!trailingSlash) { 347 baseDir += getFileSeparator(); 348 } 349 } 350 if (name != null) { 351 answer = baseDir + name; 352 } else { 353 // use a generated filename if no name provided 354 answer = baseDir + endpoint.getGeneratedFileName(exchange.getIn()); 355 } 356 357 if (endpoint.isJailStartingDirectory()) { 358 // check for file must be within starting directory (need to compact first as the name can be using relative paths via ../ etc) 359 String compatchAnswer = FileUtil.compactPath(answer); 360 String compatchBaseDir = FileUtil.compactPath(baseDir); 361 if (!compatchAnswer.startsWith(compatchBaseDir)) { 362 throw new IllegalArgumentException("Cannot write file with name: " + compatchAnswer + " as the filename is jailed to the starting directory: " + compatchBaseDir); 363 } 364 } 365 366 if (endpoint.getConfiguration().needToNormalize()) { 367 // must normalize path to cater for Windows and other OS 368 answer = normalizePath(answer); 369 } 370 371 return answer; 372 } 373 374 public String createTempFileName(Exchange exchange, String fileName) { 375 String answer = fileName; 376 377 String tempName; 378 if (exchange.getIn().getHeader(Exchange.FILE_NAME) == null) { 379 // its a generated filename then add it to header so we can evaluate the expression 380 exchange.getIn().setHeader(Exchange.FILE_NAME, FileUtil.stripPath(fileName)); 381 tempName = endpoint.getTempFileName().evaluate(exchange, String.class); 382 // and remove it again after evaluation 383 exchange.getIn().removeHeader(Exchange.FILE_NAME); 384 } else { 385 tempName = endpoint.getTempFileName().evaluate(exchange, String.class); 386 } 387 388 // check for both windows and unix separators 389 int pos = Math.max(answer.lastIndexOf("/"), answer.lastIndexOf("\\")); 390 if (pos == -1) { 391 // no path so use temp name as calculated 392 answer = tempName; 393 } else { 394 // path should be prefixed before the temp name 395 StringBuilder sb = new StringBuilder(answer.substring(0, pos + 1)); 396 sb.append(tempName); 397 answer = sb.toString(); 398 } 399 400 if (endpoint.getConfiguration().needToNormalize()) { 401 // must normalize path to cater for Windows and other OS 402 answer = normalizePath(answer); 403 } 404 405 // stack path in case the temporary file uses .. paths 406 answer = FileUtil.compactPath(answer, getFileSeparator()); 407 408 return answer; 409 } 410 411 @Override 412 protected void doStart() throws Exception { 413 ServiceHelper.startService(locks); 414 super.doStart(); 415 } 416 417 @Override 418 protected void doStop() throws Exception { 419 super.doStop(); 420 ServiceHelper.stopService(locks); 421 } 422}