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.IOException; 020import java.lang.reflect.Method; 021import java.util.ArrayList; 022import java.util.Comparator; 023import java.util.HashMap; 024import java.util.List; 025import java.util.Map; 026import java.util.concurrent.ScheduledExecutorService; 027import java.util.regex.Matcher; 028import java.util.regex.Pattern; 029 030import org.apache.camel.CamelContext; 031import org.apache.camel.Component; 032import org.apache.camel.Exchange; 033import org.apache.camel.Expression; 034import org.apache.camel.ExpressionIllegalSyntaxException; 035import org.apache.camel.LoggingLevel; 036import org.apache.camel.Message; 037import org.apache.camel.Predicate; 038import org.apache.camel.Processor; 039import org.apache.camel.component.file.strategy.FileMoveExistingStrategy; 040import org.apache.camel.impl.ScheduledPollEndpoint; 041import org.apache.camel.processor.idempotent.MemoryIdempotentRepository; 042import org.apache.camel.spi.BrowsableEndpoint; 043import org.apache.camel.spi.ExceptionHandler; 044import org.apache.camel.spi.FactoryFinder; 045import org.apache.camel.spi.IdempotentRepository; 046import org.apache.camel.spi.Language; 047import org.apache.camel.spi.UriParam; 048import org.apache.camel.util.FileUtil; 049import org.apache.camel.util.IOHelper; 050import org.apache.camel.util.ObjectHelper; 051import org.apache.camel.util.ServiceHelper; 052import org.apache.camel.util.StringHelper; 053import org.slf4j.Logger; 054import org.slf4j.LoggerFactory; 055 056/** 057 * Base class for file endpoints 058 */ 059public abstract class GenericFileEndpoint<T> extends ScheduledPollEndpoint implements BrowsableEndpoint { 060 061 protected static final String DEFAULT_STRATEGYFACTORY_CLASS = "org.apache.camel.component.file.strategy.GenericFileProcessStrategyFactory"; 062 protected static final int DEFAULT_IDEMPOTENT_CACHE_SIZE = 1000; 063 protected static final int DEFAULT_IN_PROGRESS_CACHE_SIZE = 50000; 064 065 protected final Logger log = LoggerFactory.getLogger(getClass()); 066 067 // common options 068 069 @UriParam(label = "advanced", defaultValue = "true") 070 protected boolean autoCreate = true; 071 @UriParam(label = "advanced", defaultValue = "" + FileUtil.BUFFER_SIZE) 072 protected int bufferSize = FileUtil.BUFFER_SIZE; 073 @UriParam 074 protected String charset; 075 @UriParam(javaType = "java.lang.String") 076 protected Expression fileName; 077 @UriParam 078 protected String doneFileName; 079 080 // producer options 081 082 @UriParam(label = "producer") 083 protected boolean flatten; 084 @UriParam(label = "producer", defaultValue = "Override") 085 protected GenericFileExist fileExist = GenericFileExist.Override; 086 @UriParam(label = "producer") 087 protected String tempPrefix; 088 @UriParam(label = "producer", javaType = "java.lang.String") 089 protected Expression tempFileName; 090 @UriParam(label = "producer,advanced", defaultValue = "true") 091 protected boolean eagerDeleteTargetFile = true; 092 @UriParam(label = "producer,advanced") 093 protected boolean keepLastModified; 094 @UriParam(label = "producer,advanced") 095 protected boolean allowNullBody; 096 097 // consumer options 098 099 @UriParam 100 protected GenericFileConfiguration configuration; 101 @UriParam(label = "consumer,advanced") 102 protected GenericFileProcessStrategy<T> processStrategy; 103 @UriParam(label = "consumer,advanced") 104 protected IdempotentRepository<String> inProgressRepository = MemoryIdempotentRepository.memoryIdempotentRepository(DEFAULT_IN_PROGRESS_CACHE_SIZE); 105 @UriParam(label = "consumer,advanced") 106 protected String localWorkDirectory; 107 @UriParam(label = "consumer,advanced") 108 protected boolean startingDirectoryMustExist; 109 @UriParam(label = "consumer,advanced") 110 protected boolean directoryMustExist; 111 @UriParam(label = "consumer") 112 protected boolean noop; 113 @UriParam(label = "consumer") 114 protected boolean recursive; 115 @UriParam(label = "consumer") 116 protected boolean delete; 117 @UriParam(label = "consumer") 118 protected boolean preSort; 119 @UriParam(label = "consumer,filter") 120 protected int maxMessagesPerPoll; 121 @UriParam(label = "consumer,filter", defaultValue = "true") 122 protected boolean eagerMaxMessagesPerPoll = true; 123 @UriParam(label = "consumer,filter", defaultValue = "" + Integer.MAX_VALUE) 124 protected int maxDepth = Integer.MAX_VALUE; 125 @UriParam(label = "consumer,filter") 126 protected int minDepth; 127 @UriParam(label = "consumer,filter") 128 protected String include; 129 @UriParam(label = "consumer,filter") 130 protected String exclude; 131 @UriParam(label = "consumer,filter", javaType = "java.lang.String") 132 protected Expression move; 133 @UriParam(label = "consumer", javaType = "java.lang.String") 134 protected Expression moveFailed; 135 @UriParam(label = "consumer", javaType = "java.lang.String") 136 protected Expression preMove; 137 @UriParam(label = "producer", javaType = "java.lang.String") 138 protected Expression moveExisting; 139 @UriParam(label = "producer,advanced") 140 protected FileMoveExistingStrategy moveExistingFileStrategy; 141 @UriParam(label = "consumer,filter", defaultValue = "false") 142 protected Boolean idempotent; 143 @UriParam(label = "consumer,filter", javaType = "java.lang.String") 144 protected Expression idempotentKey; 145 @UriParam(label = "consumer,filter") 146 protected IdempotentRepository<String> idempotentRepository; 147 @UriParam(label = "consumer,filter") 148 protected GenericFileFilter<T> filter; 149 @UriParam(label = "consumer,filter", javaType = "java.lang.String") 150 protected Predicate filterDirectory; 151 @UriParam(label = "consumer,filter", javaType = "java.lang.String") 152 protected Predicate filterFile; 153 @UriParam(label = "consumer,filter", defaultValue = "true") 154 protected boolean antFilterCaseSensitive = true; 155 protected volatile AntPathMatcherGenericFileFilter<T> antFilter; 156 @UriParam(label = "consumer,filter") 157 protected String antInclude; 158 @UriParam(label = "consumer,filter") 159 protected String antExclude; 160 @UriParam(label = "consumer,sort") 161 protected Comparator<GenericFile<T>> sorter; 162 @UriParam(label = "consumer,sort", javaType = "java.lang.String") 163 protected Comparator<Exchange> sortBy; 164 @UriParam(label = "consumer,sort") 165 protected boolean shuffle; 166 @UriParam(label = "consumer,lock", defaultValue = "none", enums = "none,markerFile,fileLock,rename,changed,idempotent,idempotent-changed,idempotent-rename") 167 protected String readLock = "none"; 168 @UriParam(label = "consumer,lock", defaultValue = "1000") 169 protected long readLockCheckInterval = 1000; 170 @UriParam(label = "consumer,lock", defaultValue = "10000") 171 protected long readLockTimeout = 10000; 172 @UriParam(label = "consumer,lock", defaultValue = "true") 173 protected boolean readLockMarkerFile = true; 174 @UriParam(label = "consumer,lock", defaultValue = "true") 175 protected boolean readLockDeleteOrphanLockFiles = true; 176 @UriParam(label = "consumer,lock", defaultValue = "DEBUG") 177 protected LoggingLevel readLockLoggingLevel = LoggingLevel.DEBUG; 178 @UriParam(label = "consumer,lock", defaultValue = "1") 179 protected long readLockMinLength = 1; 180 @UriParam(label = "consumer,lock", defaultValue = "0") 181 protected long readLockMinAge; 182 @UriParam(label = "consumer,lock", defaultValue = "true") 183 protected boolean readLockRemoveOnRollback = true; 184 @UriParam(label = "consumer,lock") 185 protected boolean readLockRemoveOnCommit; 186 @UriParam(label = "consumer,lock") 187 protected int readLockIdempotentReleaseDelay; 188 @UriParam(label = "consumer,lock") 189 protected boolean readLockIdempotentReleaseAsync; 190 @UriParam(label = "consumer,lock") 191 protected int readLockIdempotentReleaseAsyncPoolSize; 192 @UriParam(label = "consumer,lock") 193 protected ScheduledExecutorService readLockIdempotentReleaseExecutorService; 194 @UriParam(label = "consumer,lock") 195 protected GenericFileExclusiveReadLockStrategy<T> exclusiveReadLockStrategy; 196 @UriParam(label = "consumer,advanced") 197 protected ExceptionHandler onCompletionExceptionHandler; 198 199 private Pattern includePattern; 200 private Pattern excludePattern; 201 202 public GenericFileEndpoint() { 203 } 204 205 public GenericFileEndpoint(String endpointUri, Component component) { 206 super(endpointUri, component); 207 } 208 209 public boolean isSingleton() { 210 return true; 211 } 212 213 public abstract GenericFileConsumer<T> createConsumer(Processor processor) throws Exception; 214 215 public abstract GenericFileProducer<T> createProducer() throws Exception; 216 217 public abstract Exchange createExchange(GenericFile<T> file); 218 219 public abstract String getScheme(); 220 221 public abstract char getFileSeparator(); 222 223 public abstract boolean isAbsolute(String name); 224 225 /** 226 * Return the file name that will be auto-generated for the given message if 227 * none is provided 228 */ 229 public String getGeneratedFileName(Message message) { 230 return StringHelper.sanitize(message.getMessageId()); 231 } 232 233 /** 234 * This implementation will <b>not</b> load the file content. 235 * Any file locking is neither in use by this implementation.. 236 */ 237 @Override 238 public List<Exchange> getExchanges() { 239 final List<Exchange> answer = new ArrayList<>(); 240 241 GenericFileConsumer<?> consumer = null; 242 try { 243 // create a new consumer which can poll the exchanges we want to browse 244 // do not provide a processor as we do some custom processing 245 consumer = createConsumer(null); 246 consumer.setCustomProcessor(new Processor() { 247 @Override 248 public void process(Exchange exchange) throws Exception { 249 answer.add(exchange); 250 } 251 }); 252 // do not start scheduler, as we invoke the poll manually 253 consumer.setStartScheduler(false); 254 // start consumer 255 ServiceHelper.startService(consumer); 256 // invoke poll which performs the custom processing, so we can browse the exchanges 257 consumer.poll(); 258 } catch (Exception e) { 259 throw ObjectHelper.wrapRuntimeCamelException(e); 260 } finally { 261 try { 262 ServiceHelper.stopService(consumer); 263 } catch (Exception e) { 264 log.debug("Error stopping consumer used for browsing exchanges. This exception will be ignored", e); 265 } 266 } 267 268 return answer; 269 } 270 271 /** 272 * A strategy method to lazily create the file strategy 273 */ 274 @SuppressWarnings("unchecked") 275 protected GenericFileProcessStrategy<T> createGenericFileStrategy() { 276 Class<?> factory = null; 277 try { 278 FactoryFinder finder = getCamelContext().getFactoryFinder("META-INF/services/org/apache/camel/component/"); 279 log.trace("Using FactoryFinder: {}", finder); 280 factory = finder.findClass(getScheme(), "strategy.factory.", CamelContext.class); 281 } catch (ClassNotFoundException e) { 282 log.trace("'strategy.factory.class' not found", e); 283 } catch (IOException e) { 284 log.trace("No strategy factory defined in 'META-INF/services/org/apache/camel/component/'", e); 285 } 286 287 if (factory == null) { 288 // use default 289 try { 290 log.trace("Using ClassResolver to resolve class: {}", DEFAULT_STRATEGYFACTORY_CLASS); 291 factory = this.getCamelContext().getClassResolver().resolveClass(DEFAULT_STRATEGYFACTORY_CLASS); 292 } catch (Exception e) { 293 log.trace("Cannot load class: {}", DEFAULT_STRATEGYFACTORY_CLASS, e); 294 } 295 // fallback and us this class loader 296 try { 297 if (log.isTraceEnabled()) { 298 log.trace("Using classloader: {} to resolve class: {}", this.getClass().getClassLoader(), DEFAULT_STRATEGYFACTORY_CLASS); 299 } 300 factory = this.getCamelContext().getClassResolver().resolveClass(DEFAULT_STRATEGYFACTORY_CLASS, this.getClass().getClassLoader()); 301 } catch (Exception e) { 302 if (log.isTraceEnabled()) { 303 log.trace("Cannot load class: {} using classloader: " + this.getClass().getClassLoader(), DEFAULT_STRATEGYFACTORY_CLASS, e); 304 } 305 } 306 307 if (factory == null) { 308 throw new TypeNotPresentException(DEFAULT_STRATEGYFACTORY_CLASS + " class not found", null); 309 } 310 } 311 312 try { 313 Method factoryMethod = factory.getMethod("createGenericFileProcessStrategy", CamelContext.class, Map.class); 314 Map<String, Object> params = getParamsAsMap(); 315 log.debug("Parameters for Generic file process strategy {}", params); 316 return (GenericFileProcessStrategy<T>) ObjectHelper.invokeMethod(factoryMethod, null, getCamelContext(), params); 317 } catch (NoSuchMethodException e) { 318 throw new TypeNotPresentException(factory.getSimpleName() + ".createGenericFileProcessStrategy method not found", e); 319 } 320 } 321 322 public boolean isNoop() { 323 return noop; 324 } 325 326 /** 327 * If true, the file is not moved or deleted in any way. 328 * This option is good for readonly data, or for ETL type requirements. 329 * If noop=true, Camel will set idempotent=true as well, to avoid consuming the same files over and over again. 330 */ 331 public void setNoop(boolean noop) { 332 this.noop = noop; 333 } 334 335 public boolean isRecursive() { 336 return recursive; 337 } 338 339 /** 340 * If a directory, will look for files in all the sub-directories as well. 341 */ 342 public void setRecursive(boolean recursive) { 343 this.recursive = recursive; 344 } 345 346 public String getInclude() { 347 return include; 348 } 349 350 /** 351 * Is used to include files, if filename matches the regex pattern (matching is case in-sensitive). 352 * <p/> 353 * Notice if you use symbols such as plus sign and others you would need to configure 354 * this using the RAW() syntax if configuring this as an endpoint uri. 355 * See more details at <a href="http://camel.apache.org/how-do-i-configure-endpoints.html">configuring endpoint uris</a> 356 */ 357 public void setInclude(String include) { 358 this.include = include; 359 this.includePattern = Pattern.compile(include, Pattern.CASE_INSENSITIVE); 360 } 361 362 public Pattern getIncludePattern() { 363 return includePattern; 364 } 365 366 public String getExclude() { 367 return exclude; 368 } 369 370 /** 371 * Is used to exclude files, if filename matches the regex pattern (matching is case in-senstive). 372 * <p/> 373 * Notice if you use symbols such as plus sign and others you would need to configure 374 * this using the RAW() syntax if configuring this as an endpoint uri. 375 * See more details at <a href="http://camel.apache.org/how-do-i-configure-endpoints.html">configuring endpoint uris</a> 376 */ 377 public void setExclude(String exclude) { 378 this.exclude = exclude; 379 this.excludePattern = Pattern.compile(exclude, Pattern.CASE_INSENSITIVE); 380 } 381 382 public Pattern getExcludePattern() { 383 return this.excludePattern; 384 } 385 386 public String getAntInclude() { 387 return antInclude; 388 } 389 390 /** 391 * Ant style filter inclusion. 392 * Multiple inclusions may be specified in comma-delimited format. 393 */ 394 public void setAntInclude(String antInclude) { 395 this.antInclude = antInclude; 396 } 397 398 public String getAntExclude() { 399 return antExclude; 400 } 401 402 /** 403 * Ant style filter exclusion. If both antInclude and antExclude are used, antExclude takes precedence over antInclude. 404 * Multiple exclusions may be specified in comma-delimited format. 405 */ 406 public void setAntExclude(String antExclude) { 407 this.antExclude = antExclude; 408 } 409 410 public boolean isAntFilterCaseSensitive() { 411 return antFilterCaseSensitive; 412 } 413 414 /** 415 * Sets case sensitive flag on ant filter 416 */ 417 public void setAntFilterCaseSensitive(boolean antFilterCaseSensitive) { 418 this.antFilterCaseSensitive = antFilterCaseSensitive; 419 } 420 421 public GenericFileFilter<T> getAntFilter() { 422 return antFilter; 423 } 424 425 public boolean isPreSort() { 426 return preSort; 427 } 428 429 /** 430 * When pre-sort is enabled then the consumer will sort the file and directory names during polling, 431 * that was retrieved from the file system. You may want to do this in case you need to operate on the files 432 * in a sorted order. The pre-sort is executed before the consumer starts to filter, and accept files 433 * to process by Camel. This option is default=false meaning disabled. 434 */ 435 public void setPreSort(boolean preSort) { 436 this.preSort = preSort; 437 } 438 439 public boolean isDelete() { 440 return delete; 441 } 442 443 /** 444 * If true, the file will be deleted after it is processed successfully. 445 */ 446 public void setDelete(boolean delete) { 447 this.delete = delete; 448 } 449 450 public boolean isFlatten() { 451 return flatten; 452 } 453 454 /** 455 * Flatten is used to flatten the file name path to strip any leading paths, so it's just the file name. 456 * This allows you to consume recursively into sub-directories, but when you eg write the files to another directory 457 * they will be written in a single directory. 458 * Setting this to true on the producer enforces that any file name in CamelFileName header 459 * will be stripped for any leading paths. 460 */ 461 public void setFlatten(boolean flatten) { 462 this.flatten = flatten; 463 } 464 465 public Expression getMove() { 466 return move; 467 } 468 469 /** 470 * Expression (such as Simple Language) used to dynamically set the filename when moving it after processing. 471 * To move files into a .done subdirectory just enter .done. 472 */ 473 public void setMove(Expression move) { 474 this.move = move; 475 } 476 477 /** 478 * @see #setMove(org.apache.camel.Expression) 479 */ 480 public void setMove(String fileLanguageExpression) { 481 String expression = configureMoveOrPreMoveExpression(fileLanguageExpression); 482 this.move = createFileLanguageExpression(expression); 483 } 484 485 public Expression getMoveFailed() { 486 return moveFailed; 487 } 488 489 /** 490 * Sets the move failure expression based on Simple language. 491 * For example, to move files into a .error subdirectory use: .error. 492 * Note: When moving the files to the fail location Camel will handle the error and will not pick up the file again. 493 */ 494 public void setMoveFailed(Expression moveFailed) { 495 this.moveFailed = moveFailed; 496 } 497 498 public void setMoveFailed(String fileLanguageExpression) { 499 String expression = configureMoveOrPreMoveExpression(fileLanguageExpression); 500 this.moveFailed = createFileLanguageExpression(expression); 501 } 502 503 public Predicate getFilterDirectory() { 504 return filterDirectory; 505 } 506 507 /** 508 * Filters the directory based on Simple language. 509 * For example to filter on current date, you can use a simple date pattern such as ${date:now:yyyMMdd} 510 */ 511 public void setFilterDirectory(Predicate filterDirectory) { 512 this.filterDirectory = filterDirectory; 513 } 514 515 /** 516 * Filters the directory based on Simple language. 517 * For example to filter on current date, you can use a simple date pattern such as ${date:now:yyyMMdd} 518 * @see #setFilterDirectory(Predicate) 519 */ 520 public void setFilterDirectory(String expression) { 521 this.filterDirectory = createFileLanguagePredicate(expression); 522 } 523 524 public Predicate getFilterFile() { 525 return filterFile; 526 } 527 528 /** 529 * Filters the file based on Simple language. 530 * For example to filter on file size, you can use ${file:size} > 5000 531 */ 532 public void setFilterFile(Predicate filterFile) { 533 this.filterFile = filterFile; 534 } 535 536 /** 537 * Filters the file based on Simple language. 538 * For example to filter on file size, you can use ${file:size} > 5000 539 * @see #setFilterFile(Predicate) 540 */ 541 public void setFilterFile(String expression) { 542 this.filterFile = createFileLanguagePredicate(expression); 543 } 544 545 public Expression getPreMove() { 546 return preMove; 547 } 548 549 /** 550 * Expression (such as File Language) used to dynamically set the filename when moving it before processing. 551 * For example to move in-progress files into the order directory set this value to order. 552 */ 553 public void setPreMove(Expression preMove) { 554 this.preMove = preMove; 555 } 556 557 public void setPreMove(String fileLanguageExpression) { 558 String expression = configureMoveOrPreMoveExpression(fileLanguageExpression); 559 this.preMove = createFileLanguageExpression(expression); 560 } 561 562 public Expression getMoveExisting() { 563 return moveExisting; 564 } 565 566 /** 567 * Expression (such as File Language) used to compute file name to use when fileExist=Move is configured. 568 * To move files into a backup subdirectory just enter backup. 569 * This option only supports the following File Language tokens: "file:name", "file:name.ext", "file:name.noext", "file:onlyname", 570 * "file:onlyname.noext", "file:ext", and "file:parent". Notice the "file:parent" is not supported by the FTP component, 571 * as the FTP component can only move any existing files to a relative directory based on current dir as base. 572 */ 573 public void setMoveExisting(Expression moveExisting) { 574 this.moveExisting = moveExisting; 575 } 576 577 public FileMoveExistingStrategy getMoveExistingFileStrategy() { 578 return moveExistingFileStrategy; 579 } 580 581 /** 582 * Strategy (Custom Strategy) used to move file with special naming token to use when fileExist=Move is configured. 583 * By default, there is an implementation used if no custom strategy is provided 584 */ 585 public void setMoveExistingFileStrategy(FileMoveExistingStrategy moveExistingFileStrategy) { 586 this.moveExistingFileStrategy = moveExistingFileStrategy; 587 } 588 589 public void setMoveExisting(String fileLanguageExpression) { 590 String expression = configureMoveOrPreMoveExpression(fileLanguageExpression); 591 this.moveExisting = createFileLanguageExpression(expression); 592 } 593 594 public Expression getFileName() { 595 return fileName; 596 } 597 598 /** 599 * Use Expression such as File Language to dynamically set the filename. 600 * For consumers, it's used as a filename filter. 601 * For producers, it's used to evaluate the filename to write. 602 * If an expression is set, it take precedence over the CamelFileName header. (Note: The header itself can also be an Expression). 603 * The expression options support both String and Expression types. 604 * If the expression is a String type, it is always evaluated using the File Language. 605 * If the expression is an Expression type, the specified Expression type is used - this allows you, 606 * for instance, to use OGNL expressions. For the consumer, you can use it to filter filenames, 607 * so you can for instance consume today's file using the File Language syntax: mydata-${date:now:yyyyMMdd}.txt. 608 * The producers support the CamelOverruleFileName header which takes precedence over any existing CamelFileName header; 609 * the CamelOverruleFileName is a header that is used only once, and makes it easier as this avoids to temporary 610 * store CamelFileName and have to restore it afterwards. 611 */ 612 public void setFileName(Expression fileName) { 613 this.fileName = fileName; 614 } 615 616 public void setFileName(String fileLanguageExpression) { 617 this.fileName = createFileLanguageExpression(fileLanguageExpression); 618 } 619 620 public String getDoneFileName() { 621 return doneFileName; 622 } 623 624 /** 625 * Producer: If provided, then Camel will write a 2nd done file when the original file has been written. 626 * The done file will be empty. This option configures what file name to use. 627 * Either you can specify a fixed name. Or you can use dynamic placeholders. 628 * The done file will always be written in the same folder as the original file. 629 * <p/> 630 * Consumer: If provided, Camel will only consume files if a done file exists. 631 * This option configures what file name to use. Either you can specify a fixed name. 632 * Or you can use dynamic placeholders.The done file is always expected in the same folder 633 * as the original file. 634 * <p/> 635 * Only ${file.name} and ${file.name.noext} is supported as dynamic placeholders. 636 */ 637 public void setDoneFileName(String doneFileName) { 638 this.doneFileName = doneFileName; 639 } 640 641 public Boolean isIdempotent() { 642 return idempotent != null ? idempotent : false; 643 } 644 645 public String getCharset() { 646 return charset; 647 } 648 649 /** 650 * This option is used to specify the encoding of the file. 651 * You can use this on the consumer, to specify the encodings of the files, which allow Camel to know the charset 652 * it should load the file content in case the file content is being accessed. 653 * Likewise when writing a file, you can use this option to specify which charset to write the file as well. 654 * Do mind that when writing the file Camel may have to read the message content into memory to be able to 655 * convert the data into the configured charset, so do not use this if you have big messages. 656 */ 657 public void setCharset(String charset) { 658 IOHelper.validateCharset(charset); 659 this.charset = charset; 660 } 661 662 protected boolean isIdempotentSet() { 663 return idempotent != null; 664 } 665 666 /** 667 * Option to use the Idempotent Consumer EIP pattern to let Camel skip already processed files. 668 * Will by default use a memory based LRUCache that holds 1000 entries. If noop=true then idempotent will be enabled 669 * as well to avoid consuming the same files over and over again. 670 */ 671 public void setIdempotent(Boolean idempotent) { 672 this.idempotent = idempotent; 673 } 674 675 public Expression getIdempotentKey() { 676 return idempotentKey; 677 } 678 679 /** 680 * To use a custom idempotent key. By default the absolute path of the file is used. 681 * You can use the File Language, for example to use the file name and file size, you can do: 682 * <tt>idempotentKey=${file:name}-${file:size}</tt> 683 */ 684 public void setIdempotentKey(Expression idempotentKey) { 685 this.idempotentKey = idempotentKey; 686 } 687 688 public void setIdempotentKey(String expression) { 689 this.idempotentKey = createFileLanguageExpression(expression); 690 } 691 692 public IdempotentRepository<String> getIdempotentRepository() { 693 return idempotentRepository; 694 } 695 696 /** 697 * A pluggable repository org.apache.camel.spi.IdempotentRepository which by default use MemoryMessageIdRepository 698 * if none is specified and idempotent is true. 699 */ 700 public void setIdempotentRepository(IdempotentRepository<String> idempotentRepository) { 701 this.idempotentRepository = idempotentRepository; 702 } 703 704 public GenericFileFilter<T> getFilter() { 705 return filter; 706 } 707 708 /** 709 * Pluggable filter as a org.apache.camel.component.file.GenericFileFilter class. 710 * Will skip files if filter returns false in its accept() method. 711 */ 712 public void setFilter(GenericFileFilter<T> filter) { 713 this.filter = filter; 714 } 715 716 public Comparator<GenericFile<T>> getSorter() { 717 return sorter; 718 } 719 720 /** 721 * Pluggable sorter as a java.util.Comparator<org.apache.camel.component.file.GenericFile> class. 722 */ 723 public void setSorter(Comparator<GenericFile<T>> sorter) { 724 this.sorter = sorter; 725 } 726 727 public Comparator<Exchange> getSortBy() { 728 return sortBy; 729 } 730 731 /** 732 * Built-in sort by using the File Language. 733 * Supports nested sorts, so you can have a sort by file name and as a 2nd group sort by modified date. 734 */ 735 public void setSortBy(Comparator<Exchange> sortBy) { 736 this.sortBy = sortBy; 737 } 738 739 public void setSortBy(String expression) { 740 setSortBy(expression, false); 741 } 742 743 public void setSortBy(String expression, boolean reverse) { 744 setSortBy(GenericFileDefaultSorter.sortByFileLanguage(getCamelContext(), expression, reverse)); 745 } 746 747 public boolean isShuffle() { 748 return shuffle; 749 } 750 751 /** 752 * To shuffle the list of files (sort in random order) 753 */ 754 public void setShuffle(boolean shuffle) { 755 this.shuffle = shuffle; 756 } 757 758 public String getTempPrefix() { 759 return tempPrefix; 760 } 761 762 /** 763 * This option is used to write the file using a temporary name and then, after the write is complete, 764 * rename it to the real name. Can be used to identify files being written and also avoid consumers 765 * (not using exclusive read locks) reading in progress files. Is often used by FTP when uploading big files. 766 */ 767 public void setTempPrefix(String tempPrefix) { 768 this.tempPrefix = tempPrefix; 769 // use only name as we set a prefix in from on the name 770 setTempFileName(tempPrefix + "${file:onlyname}"); 771 } 772 773 public Expression getTempFileName() { 774 return tempFileName; 775 } 776 777 /** 778 * The same as tempPrefix option but offering a more fine grained control on the naming of the temporary filename as it uses the File Language. 779 */ 780 public void setTempFileName(Expression tempFileName) { 781 this.tempFileName = tempFileName; 782 } 783 784 public void setTempFileName(String tempFileNameExpression) { 785 this.tempFileName = createFileLanguageExpression(tempFileNameExpression); 786 } 787 788 public boolean isEagerDeleteTargetFile() { 789 return eagerDeleteTargetFile; 790 } 791 792 /** 793 * Whether or not to eagerly delete any existing target file. 794 * This option only applies when you use fileExists=Override and the tempFileName option as well. 795 * You can use this to disable (set it to false) deleting the target file before the temp file is written. 796 * For example you may write big files and want the target file to exists during the temp file is being written. 797 * This ensure the target file is only deleted until the very last moment, just before the temp file is being 798 * renamed to the target filename. This option is also used to control whether to delete any existing files when 799 * fileExist=Move is enabled, and an existing file exists. 800 * If this option copyAndDeleteOnRenameFails false, then an exception will be thrown if an existing file existed, 801 * if its true, then the existing file is deleted before the move operation. 802 */ 803 public void setEagerDeleteTargetFile(boolean eagerDeleteTargetFile) { 804 this.eagerDeleteTargetFile = eagerDeleteTargetFile; 805 } 806 807 public GenericFileConfiguration getConfiguration() { 808 if (configuration == null) { 809 configuration = new GenericFileConfiguration(); 810 } 811 return configuration; 812 } 813 814 public void setConfiguration(GenericFileConfiguration configuration) { 815 this.configuration = configuration; 816 } 817 818 public GenericFileExclusiveReadLockStrategy<T> getExclusiveReadLockStrategy() { 819 return exclusiveReadLockStrategy; 820 } 821 822 /** 823 * Pluggable read-lock as a org.apache.camel.component.file.GenericFileExclusiveReadLockStrategy implementation. 824 */ 825 public void setExclusiveReadLockStrategy(GenericFileExclusiveReadLockStrategy<T> exclusiveReadLockStrategy) { 826 this.exclusiveReadLockStrategy = exclusiveReadLockStrategy; 827 } 828 829 public String getReadLock() { 830 return readLock; 831 } 832 833 /** 834 * Used by consumer, to only poll the files if it has exclusive read-lock on the file (i.e. the file is not in-progress or being written). 835 * Camel will wait until the file lock is granted. 836 * <p/> 837 * This option provides the build in strategies: 838 * <ul> 839 * <li>none - No read lock is in use 840 * <li>markerFile - Camel creates a marker file (fileName.camelLock) and then holds a lock on it. This option is not available for the FTP component 841 * <li>changed - Changed is using file length/modification timestamp to detect whether the file is currently being copied or not. Will at least use 1 sec 842 * to determine this, so this option cannot consume files as fast as the others, but can be more reliable as the JDK IO API cannot 843 * always determine whether a file is currently being used by another process. The option readLockCheckInterval can be used to set the check frequency.</li> 844 * <li>fileLock - is for using java.nio.channels.FileLock. This option is not avail for the FTP component. This approach should be avoided when accessing 845 * a remote file system via a mount/share unless that file system supports distributed file locks.</li> 846 * <li>rename - rename is for using a try to rename the file as a test if we can get exclusive read-lock.</li> 847 * <li>idempotent - (only for file component) idempotent is for using a idempotentRepository as the read-lock. 848 * This allows to use read locks that supports clustering if the idempotent repository implementation supports that.</li> 849 * <li>idempotent-changed - (only for file component) idempotent-changed is for using a idempotentRepository and changed as the combined read-lock. 850 * This allows to use read locks that supports clustering if the idempotent repository implementation supports that.</li> 851 * <li>idempotent-rename - (only for file component) idempotent-rename is for using a idempotentRepository and rename as the combined read-lock. 852 * This allows to use read locks that supports clustering if the idempotent repository implementation supports that.</li> 853 * </ul> 854 * Notice: The various read locks is not all suited to work in clustered mode, where concurrent consumers on different nodes is competing 855 * for the same files on a shared file system. The markerFile using a close to atomic operation to create the empty marker file, 856 * but its not guaranteed to work in a cluster. The fileLock may work better but then the file system need to support distributed file locks, and so on. 857 * Using the idempotent read lock can support clustering if the idempotent repository supports clustering, such as Hazelcast Component or Infinispan. 858 */ 859 public void setReadLock(String readLock) { 860 this.readLock = readLock; 861 } 862 863 public long getReadLockCheckInterval() { 864 return readLockCheckInterval; 865 } 866 867 /** 868 * Interval in millis for the read-lock, if supported by the read lock. 869 * This interval is used for sleeping between attempts to acquire the read lock. 870 * For example when using the changed read lock, you can set a higher interval period to cater for slow writes. 871 * The default of 1 sec. may be too fast if the producer is very slow writing the file. 872 * <p/> 873 * Notice: For FTP the default readLockCheckInterval is 5000. 874 * <p/> 875 * The readLockTimeout value must be higher than readLockCheckInterval, but a rule of thumb is to have a timeout 876 * that is at least 2 or more times higher than the readLockCheckInterval. This is needed to ensure that amble 877 * time is allowed for the read lock process to try to grab the lock before the timeout was hit. 878 */ 879 public void setReadLockCheckInterval(long readLockCheckInterval) { 880 this.readLockCheckInterval = readLockCheckInterval; 881 } 882 883 public long getReadLockTimeout() { 884 return readLockTimeout; 885 } 886 887 /** 888 * Optional timeout in millis for the read-lock, if supported by the read-lock. 889 * If the read-lock could not be granted and the timeout triggered, then Camel will skip the file. 890 * At next poll Camel, will try the file again, and this time maybe the read-lock could be granted. 891 * Use a value of 0 or lower to indicate forever. Currently fileLock, changed and rename support the timeout. 892 * <p/> 893 * Notice: For FTP the default readLockTimeout value is 20000 instead of 10000. 894 * <p/> 895 * The readLockTimeout value must be higher than readLockCheckInterval, but a rule of thumb is to have a timeout 896 * that is at least 2 or more times higher than the readLockCheckInterval. This is needed to ensure that amble 897 * time is allowed for the read lock process to try to grab the lock before the timeout was hit. 898 */ 899 public void setReadLockTimeout(long readLockTimeout) { 900 this.readLockTimeout = readLockTimeout; 901 } 902 903 public boolean isReadLockMarkerFile() { 904 return readLockMarkerFile; 905 } 906 907 /** 908 * Whether to use marker file with the changed, rename, or exclusive read lock types. 909 * By default a marker file is used as well to guard against other processes picking up the same files. 910 * This behavior can be turned off by setting this option to false. 911 * For example if you do not want to write marker files to the file systems by the Camel application. 912 */ 913 public void setReadLockMarkerFile(boolean readLockMarkerFile) { 914 this.readLockMarkerFile = readLockMarkerFile; 915 } 916 917 public boolean isReadLockDeleteOrphanLockFiles() { 918 return readLockDeleteOrphanLockFiles; 919 } 920 921 /** 922 * Whether or not read lock with marker files should upon startup delete any orphan read lock files, which may 923 * have been left on the file system, if Camel was not properly shutdown (such as a JVM crash). 924 * <p/> 925 * If turning this option to <tt>false</tt> then any orphaned lock file will cause Camel to not attempt to pickup 926 * that file, this could also be due another node is concurrently reading files from the same shared directory. 927 */ 928 public void setReadLockDeleteOrphanLockFiles(boolean readLockDeleteOrphanLockFiles) { 929 this.readLockDeleteOrphanLockFiles = readLockDeleteOrphanLockFiles; 930 } 931 932 public LoggingLevel getReadLockLoggingLevel() { 933 return readLockLoggingLevel; 934 } 935 936 /** 937 * Logging level used when a read lock could not be acquired. 938 * By default a WARN is logged. 939 * You can change this level, for example to OFF to not have any logging. 940 * This option is only applicable for readLock of types: changed, fileLock, idempotent, idempotent-changed, idempotent-rename, rename. 941 */ 942 public void setReadLockLoggingLevel(LoggingLevel readLockLoggingLevel) { 943 this.readLockLoggingLevel = readLockLoggingLevel; 944 } 945 946 public long getReadLockMinLength() { 947 return readLockMinLength; 948 } 949 950 /** 951 * This option is applied only for readLock=changed. It allows you to configure a minimum file length. 952 * By default Camel expects the file to contain data, and thus the default value is 1. 953 * You can set this option to zero, to allow consuming zero-length files. 954 */ 955 public void setReadLockMinLength(long readLockMinLength) { 956 this.readLockMinLength = readLockMinLength; 957 } 958 959 public long getReadLockMinAge() { 960 return readLockMinAge; 961 } 962 963 /** 964 * This option is applied only for readLock=changed. 965 * It allows to specify a minimum age the file must be before attempting to acquire the read lock. 966 * For example use readLockMinAge=300s to require the file is at last 5 minutes old. 967 * This can speedup the changed read lock as it will only attempt to acquire files which are at least that given age. 968 */ 969 public void setReadLockMinAge(long readLockMinAge) { 970 this.readLockMinAge = readLockMinAge; 971 } 972 973 public boolean isReadLockRemoveOnRollback() { 974 return readLockRemoveOnRollback; 975 } 976 977 /** 978 * This option is applied only for readLock=idempotent. 979 * It allows to specify whether to remove the file name entry from the idempotent repository 980 * when processing the file failed and a rollback happens. 981 * If this option is false, then the file name entry is confirmed (as if the file did a commit). 982 */ 983 public void setReadLockRemoveOnRollback(boolean readLockRemoveOnRollback) { 984 this.readLockRemoveOnRollback = readLockRemoveOnRollback; 985 } 986 987 public boolean isReadLockRemoveOnCommit() { 988 return readLockRemoveOnCommit; 989 } 990 991 /** 992 * This option is applied only for readLock=idempotent. 993 * It allows to specify whether to remove the file name entry from the idempotent repository 994 * when processing the file is succeeded and a commit happens. 995 * <p/> 996 * By default the file is not removed which ensures that any race-condition do not occur so another active 997 * node may attempt to grab the file. Instead the idempotent repository may support eviction strategies 998 * that you can configure to evict the file name entry after X minutes - this ensures no problems with race conditions. 999 * <p/> 1000 * See more details at the readLockIdempotentReleaseDelay option. 1001 */ 1002 public void setReadLockRemoveOnCommit(boolean readLockRemoveOnCommit) { 1003 this.readLockRemoveOnCommit = readLockRemoveOnCommit; 1004 } 1005 1006 /** 1007 * Whether to delay the release task for a period of millis. 1008 * <p/> 1009 * This can be used to delay the release tasks to expand the window when a file is regarded as read-locked, 1010 * in an active/active cluster scenario with a shared idempotent repository, to ensure other nodes cannot potentially scan and acquire 1011 * the same file, due to race-conditions. By expanding the time-window of the release tasks helps prevents these situations. 1012 * Note delaying is only needed if you have configured readLockRemoveOnCommit to true. 1013 */ 1014 public void setReadLockIdempotentReleaseDelay(int readLockIdempotentReleaseDelay) { 1015 this.readLockIdempotentReleaseDelay = readLockIdempotentReleaseDelay; 1016 } 1017 1018 public boolean isReadLockIdempotentReleaseAsync() { 1019 return readLockIdempotentReleaseAsync; 1020 } 1021 1022 /** 1023 * Whether the delayed release task should be synchronous or asynchronous. 1024 * <p/> 1025 * See more details at the readLockIdempotentReleaseDelay option. 1026 */ 1027 public void setReadLockIdempotentReleaseAsync(boolean readLockIdempotentReleaseAsync) { 1028 this.readLockIdempotentReleaseAsync = readLockIdempotentReleaseAsync; 1029 } 1030 1031 public int getReadLockIdempotentReleaseAsyncPoolSize() { 1032 return readLockIdempotentReleaseAsyncPoolSize; 1033 } 1034 1035 /** 1036 * The number of threads in the scheduled thread pool when using asynchronous release tasks. 1037 * Using a default of 1 core threads should be sufficient in almost all use-cases, only set this to a higher value 1038 * if either updating the idempotent repository is slow, or there are a lot of files to process. 1039 * This option is not in-use if you use a shared thread pool by configuring the readLockIdempotentReleaseExecutorService option. 1040 * <p/> 1041 * See more details at the readLockIdempotentReleaseDelay option. 1042 */ 1043 public void setReadLockIdempotentReleaseAsyncPoolSize(int readLockIdempotentReleaseAsyncPoolSize) { 1044 this.readLockIdempotentReleaseAsyncPoolSize = readLockIdempotentReleaseAsyncPoolSize; 1045 } 1046 1047 public ScheduledExecutorService getReadLockIdempotentReleaseExecutorService() { 1048 return readLockIdempotentReleaseExecutorService; 1049 } 1050 1051 /** 1052 * To use a custom and shared thread pool for asynchronous release tasks. 1053 * <p/> 1054 * See more details at the readLockIdempotentReleaseDelay option. 1055 */ 1056 public void setReadLockIdempotentReleaseExecutorService(ScheduledExecutorService readLockIdempotentReleaseExecutorService) { 1057 this.readLockIdempotentReleaseExecutorService = readLockIdempotentReleaseExecutorService; 1058 } 1059 1060 public int getBufferSize() { 1061 return bufferSize; 1062 } 1063 1064 /** 1065 * Write buffer sized in bytes. 1066 */ 1067 public void setBufferSize(int bufferSize) { 1068 if (bufferSize <= 0) { 1069 throw new IllegalArgumentException("BufferSize must be a positive value, was " + bufferSize); 1070 } 1071 this.bufferSize = bufferSize; 1072 } 1073 1074 public GenericFileExist getFileExist() { 1075 return fileExist; 1076 } 1077 1078 /** 1079 * What to do if a file already exists with the same name. 1080 * 1081 * Override, which is the default, replaces the existing file. 1082 * <ul> 1083 * <li>Append - adds content to the existing file.</li> 1084 * <li>Fail - throws a GenericFileOperationException, indicating that there is already an existing file.</li> 1085 * <li>Ignore - silently ignores the problem and does not override the existing file, but assumes everything is okay.</li> 1086 * <li>Move - option requires to use the moveExisting option to be configured as well. 1087 * The option eagerDeleteTargetFile can be used to control what to do if an moving the file, and there exists already an existing file, 1088 * otherwise causing the move operation to fail. 1089 * The Move option will move any existing files, before writing the target file.</li> 1090 * <li>TryRename is only applicable if tempFileName option is in use. This allows to try renaming the file from the temporary name to the actual name, 1091 * without doing any exists check. This check may be faster on some file systems and especially FTP servers.</li> 1092 * </ul> 1093 */ 1094 public void setFileExist(GenericFileExist fileExist) { 1095 this.fileExist = fileExist; 1096 } 1097 1098 public boolean isAutoCreate() { 1099 return autoCreate; 1100 } 1101 1102 /** 1103 * Automatically create missing directories in the file's pathname. For the file consumer, that means creating the starting directory. 1104 * For the file producer, it means the directory the files should be written to. 1105 */ 1106 public void setAutoCreate(boolean autoCreate) { 1107 this.autoCreate = autoCreate; 1108 } 1109 1110 public boolean isStartingDirectoryMustExist() { 1111 return startingDirectoryMustExist; 1112 } 1113 1114 /** 1115 * Whether the starting directory must exist. Mind that the autoCreate option is default enabled, 1116 * which means the starting directory is normally auto created if it doesn't exist. 1117 * You can disable autoCreate and enable this to ensure the starting directory must exist. Will thrown an exception if the directory doesn't exist. 1118 */ 1119 public void setStartingDirectoryMustExist(boolean startingDirectoryMustExist) { 1120 this.startingDirectoryMustExist = startingDirectoryMustExist; 1121 } 1122 1123 public boolean isDirectoryMustExist() { 1124 return directoryMustExist; 1125 } 1126 1127 /** 1128 * Similar to startingDirectoryMustExist but this applies during polling recursive sub directories. 1129 */ 1130 public void setDirectoryMustExist(boolean directoryMustExist) { 1131 this.directoryMustExist = directoryMustExist; 1132 } 1133 1134 public GenericFileProcessStrategy<T> getProcessStrategy() { 1135 return processStrategy; 1136 } 1137 1138 /** 1139 * A pluggable org.apache.camel.component.file.GenericFileProcessStrategy allowing you to implement your own readLock option or similar. 1140 * Can also be used when special conditions must be met before a file can be consumed, such as a special ready file exists. 1141 * If this option is set then the readLock option does not apply. 1142 */ 1143 public void setProcessStrategy(GenericFileProcessStrategy<T> processStrategy) { 1144 this.processStrategy = processStrategy; 1145 } 1146 1147 public String getLocalWorkDirectory() { 1148 return localWorkDirectory; 1149 } 1150 1151 /** 1152 * When consuming, a local work directory can be used to store the remote file content directly in local files, 1153 * to avoid loading the content into memory. This is beneficial, if you consume a very big remote file and thus can conserve memory. 1154 */ 1155 public void setLocalWorkDirectory(String localWorkDirectory) { 1156 this.localWorkDirectory = localWorkDirectory; 1157 } 1158 1159 public int getMaxMessagesPerPoll() { 1160 return maxMessagesPerPoll; 1161 } 1162 1163 /** 1164 * To define a maximum messages to gather per poll. 1165 * By default no maximum is set. Can be used to set a limit of e.g. 1000 to avoid when starting up the server that there are thousands of files. 1166 * Set a value of 0 or negative to disabled it. 1167 * Notice: If this option is in use then the File and FTP components will limit before any sorting. 1168 * For example if you have 100000 files and use maxMessagesPerPoll=500, then only the first 500 files will be picked up, and then sorted. 1169 * You can use the eagerMaxMessagesPerPoll option and set this to false to allow to scan all files first and then sort afterwards. 1170 */ 1171 public void setMaxMessagesPerPoll(int maxMessagesPerPoll) { 1172 this.maxMessagesPerPoll = maxMessagesPerPoll; 1173 } 1174 1175 public boolean isEagerMaxMessagesPerPoll() { 1176 return eagerMaxMessagesPerPoll; 1177 } 1178 1179 /** 1180 * Allows for controlling whether the limit from maxMessagesPerPoll is eager or not. 1181 * If eager then the limit is during the scanning of files. Where as false would scan all files, and then perform sorting. 1182 * Setting this option to false allows for sorting all files first, and then limit the poll. Mind that this requires a 1183 * higher memory usage as all file details are in memory to perform the sorting. 1184 */ 1185 public void setEagerMaxMessagesPerPoll(boolean eagerMaxMessagesPerPoll) { 1186 this.eagerMaxMessagesPerPoll = eagerMaxMessagesPerPoll; 1187 } 1188 1189 public int getMaxDepth() { 1190 return maxDepth; 1191 } 1192 1193 /** 1194 * The maximum depth to traverse when recursively processing a directory. 1195 */ 1196 public void setMaxDepth(int maxDepth) { 1197 this.maxDepth = maxDepth; 1198 } 1199 1200 public int getMinDepth() { 1201 return minDepth; 1202 } 1203 1204 /** 1205 * The minimum depth to start processing when recursively processing a directory. 1206 * Using minDepth=1 means the base directory. Using minDepth=2 means the first sub directory. 1207 */ 1208 public void setMinDepth(int minDepth) { 1209 this.minDepth = minDepth; 1210 } 1211 1212 public IdempotentRepository<String> getInProgressRepository() { 1213 return inProgressRepository; 1214 } 1215 1216 /** 1217 * A pluggable in-progress repository org.apache.camel.spi.IdempotentRepository. 1218 * The in-progress repository is used to account the current in progress files being consumed. By default a memory based repository is used. 1219 */ 1220 public void setInProgressRepository(IdempotentRepository<String> inProgressRepository) { 1221 this.inProgressRepository = inProgressRepository; 1222 } 1223 1224 public boolean isKeepLastModified() { 1225 return keepLastModified; 1226 } 1227 1228 /** 1229 * Will keep the last modified timestamp from the source file (if any). 1230 * Will use the Exchange.FILE_LAST_MODIFIED header to located the timestamp. 1231 * This header can contain either a java.util.Date or long with the timestamp. 1232 * If the timestamp exists and the option is enabled it will set this timestamp on the written file. 1233 * Note: This option only applies to the file producer. You cannot use this option with any of the ftp producers. 1234 */ 1235 public void setKeepLastModified(boolean keepLastModified) { 1236 this.keepLastModified = keepLastModified; 1237 } 1238 1239 public boolean isAllowNullBody() { 1240 return allowNullBody; 1241 } 1242 1243 /** 1244 * Used to specify if a null body is allowed during file writing. 1245 * If set to true then an empty file will be created, when set to false, and attempting to send a null body to the file component, 1246 * a GenericFileWriteException of 'Cannot write null body to file.' will be thrown. 1247 * If the `fileExist` option is set to 'Override', then the file will be truncated, and if set to `append` the file will remain unchanged. 1248 */ 1249 public void setAllowNullBody(boolean allowNullBody) { 1250 this.allowNullBody = allowNullBody; 1251 } 1252 1253 public ExceptionHandler getOnCompletionExceptionHandler() { 1254 return onCompletionExceptionHandler; 1255 } 1256 1257 /** 1258 * To use a custom {@link org.apache.camel.spi.ExceptionHandler} to handle any thrown exceptions that happens 1259 * during the file on completion process where the consumer does either a commit or rollback. The default 1260 * implementation will log any exception at WARN level and ignore. 1261 */ 1262 public void setOnCompletionExceptionHandler(ExceptionHandler onCompletionExceptionHandler) { 1263 this.onCompletionExceptionHandler = onCompletionExceptionHandler; 1264 } 1265 1266 /** 1267 * Configures the given message with the file which sets the body to the 1268 * file object. 1269 */ 1270 public void configureMessage(GenericFile<T> file, Message message) { 1271 message.setBody(file); 1272 1273 if (flatten) { 1274 // when flatten the file name should not contain any paths 1275 message.setHeader(Exchange.FILE_NAME, file.getFileNameOnly()); 1276 } else { 1277 // compute name to set on header that should be relative to starting directory 1278 String name = file.isAbsolute() ? file.getAbsoluteFilePath() : file.getRelativeFilePath(); 1279 1280 // skip leading endpoint configured directory 1281 String endpointPath = getConfiguration().getDirectory() + getFileSeparator(); 1282 1283 // need to normalize paths to ensure we can match using startsWith 1284 endpointPath = FileUtil.normalizePath(endpointPath); 1285 String copyOfName = FileUtil.normalizePath(name); 1286 if (ObjectHelper.isNotEmpty(endpointPath) && copyOfName.startsWith(endpointPath)) { 1287 name = name.substring(endpointPath.length()); 1288 } 1289 1290 // adjust filename 1291 message.setHeader(Exchange.FILE_NAME, name); 1292 } 1293 } 1294 1295 /** 1296 * Set up the exchange properties with the options of the file endpoint 1297 */ 1298 public void configureExchange(Exchange exchange) { 1299 // Now we just set the charset property here 1300 if (getCharset() != null) { 1301 exchange.setProperty(Exchange.CHARSET_NAME, getCharset()); 1302 } 1303 } 1304 1305 /** 1306 * Strategy to configure the move, preMove, or moveExisting option based on a String input. 1307 * 1308 * @param expression the original string input 1309 * @return configured string or the original if no modifications is needed 1310 */ 1311 protected String configureMoveOrPreMoveExpression(String expression) { 1312 // if the expression already have ${ } placeholders then pass it unmodified 1313 if (StringHelper.hasStartToken(expression, "simple")) { 1314 return expression; 1315 } 1316 1317 // remove trailing slash 1318 expression = FileUtil.stripTrailingSeparator(expression); 1319 1320 StringBuilder sb = new StringBuilder(); 1321 1322 // if relative then insert start with the parent folder 1323 if (!isAbsolute(expression)) { 1324 sb.append("${file:parent}"); 1325 sb.append(getFileSeparator()); 1326 } 1327 // insert the directory the end user provided 1328 sb.append(expression); 1329 // append only the filename (file:name can contain a relative path, so we must use onlyname) 1330 sb.append(getFileSeparator()); 1331 sb.append("${file:onlyname}"); 1332 1333 return sb.toString(); 1334 } 1335 1336 protected Map<String, Object> getParamsAsMap() { 1337 Map<String, Object> params = new HashMap<>(); 1338 1339 if (isNoop()) { 1340 params.put("noop", Boolean.toString(true)); 1341 } 1342 if (isDelete()) { 1343 params.put("delete", Boolean.toString(true)); 1344 } 1345 if (move != null) { 1346 params.put("move", move); 1347 } 1348 if (moveFailed != null) { 1349 params.put("moveFailed", moveFailed); 1350 } 1351 if (preMove != null) { 1352 params.put("preMove", preMove); 1353 } 1354 if (exclusiveReadLockStrategy != null) { 1355 params.put("exclusiveReadLockStrategy", exclusiveReadLockStrategy); 1356 } 1357 if (readLock != null) { 1358 params.put("readLock", readLock); 1359 } 1360 if ("idempotent".equals(readLock) || "idempotent-changed".equals(readLock) || "idempotent-rename".equals(readLock)) { 1361 params.put("readLockIdempotentRepository", idempotentRepository); 1362 } 1363 if (readLockCheckInterval > 0) { 1364 params.put("readLockCheckInterval", readLockCheckInterval); 1365 } 1366 if (readLockTimeout > 0) { 1367 params.put("readLockTimeout", readLockTimeout); 1368 } 1369 params.put("readLockMarkerFile", readLockMarkerFile); 1370 params.put("readLockDeleteOrphanLockFiles", readLockDeleteOrphanLockFiles); 1371 params.put("readLockMinLength", readLockMinLength); 1372 params.put("readLockLoggingLevel", readLockLoggingLevel); 1373 params.put("readLockMinAge", readLockMinAge); 1374 params.put("readLockRemoveOnRollback", readLockRemoveOnRollback); 1375 params.put("readLockRemoveOnCommit", readLockRemoveOnCommit); 1376 if (readLockIdempotentReleaseDelay > 0) { 1377 params.put("readLockIdempotentReleaseDelay", readLockIdempotentReleaseDelay); 1378 } 1379 params.put("readLockIdempotentReleaseAsync", readLockIdempotentReleaseAsync); 1380 if (readLockIdempotentReleaseAsyncPoolSize > 0) { 1381 params.put("readLockIdempotentReleaseAsyncPoolSize", readLockIdempotentReleaseAsyncPoolSize); 1382 } 1383 if (readLockIdempotentReleaseExecutorService != null) { 1384 params.put("readLockIdempotentReleaseExecutorService", readLockIdempotentReleaseExecutorService); 1385 } 1386 return params; 1387 } 1388 1389 private Expression createFileLanguageExpression(String expression) { 1390 Language language; 1391 // only use file language if the name is complex (eg. using $) 1392 if (expression.contains("$")) { 1393 language = getCamelContext().resolveLanguage("file"); 1394 } else { 1395 language = getCamelContext().resolveLanguage("constant"); 1396 } 1397 return language.createExpression(expression); 1398 } 1399 1400 private Predicate createFileLanguagePredicate(String expression) { 1401 Language language = getCamelContext().resolveLanguage("file"); 1402 return language.createPredicate(expression); 1403 } 1404 1405 /** 1406 * Creates the associated name of the done file based on the given file name. 1407 * <p/> 1408 * This method should only be invoked if a done filename property has been set on this endpoint. 1409 * 1410 * @param fileName the file name 1411 * @return name of the associated done file name 1412 */ 1413 protected String createDoneFileName(String fileName) { 1414 String pattern = getDoneFileName(); 1415 StringHelper.notEmpty(pattern, "doneFileName", pattern); 1416 1417 // we only support ${file:name} or ${file:name.noext} as dynamic placeholders for done files 1418 String path = FileUtil.onlyPath(fileName); 1419 String onlyName = Matcher.quoteReplacement(FileUtil.stripPath(fileName)); 1420 1421 pattern = pattern.replaceFirst("\\$\\{file:name\\}", onlyName); 1422 pattern = pattern.replaceFirst("\\$simple\\{file:name\\}", onlyName); 1423 pattern = pattern.replaceFirst("\\$\\{file:name.noext\\}", FileUtil.stripExt(onlyName, true)); 1424 pattern = pattern.replaceFirst("\\$simple\\{file:name.noext\\}", FileUtil.stripExt(onlyName, true)); 1425 1426 // must be able to resolve all placeholders supported 1427 if (StringHelper.hasStartToken(pattern, "simple")) { 1428 throw new ExpressionIllegalSyntaxException(fileName + ". Cannot resolve reminder: " + pattern); 1429 } 1430 1431 String answer = pattern; 1432 if (ObjectHelper.isNotEmpty(path) && ObjectHelper.isNotEmpty(pattern)) { 1433 // done file must always be in same directory as the real file name 1434 answer = path + getFileSeparator() + pattern; 1435 } 1436 1437 if (getConfiguration().needToNormalize()) { 1438 // must normalize path to cater for Windows and other OS 1439 answer = FileUtil.normalizePath(answer); 1440 } 1441 1442 return answer; 1443 } 1444 1445 /** 1446 * Is the given file a done file? 1447 * <p/> 1448 * This method should only be invoked if a done filename property has been set on this endpoint. 1449 * 1450 * @param fileName the file name 1451 * @return <tt>true</tt> if its a done file, <tt>false</tt> otherwise 1452 */ 1453 protected boolean isDoneFile(String fileName) { 1454 String pattern = getDoneFileName(); 1455 StringHelper.notEmpty(pattern, "doneFileName", pattern); 1456 1457 if (!StringHelper.hasStartToken(pattern, "simple")) { 1458 // no tokens, so just match names directly 1459 return pattern.equals(fileName); 1460 } 1461 1462 // the static part of the pattern, is that a prefix or suffix? 1463 // its a prefix if ${ start token is not at the start of the pattern 1464 boolean prefix = pattern.indexOf("${") > 0; 1465 1466 // remove dynamic parts of the pattern so we only got the static part left 1467 pattern = pattern.replaceFirst("\\$\\{file:name\\}", ""); 1468 pattern = pattern.replaceFirst("\\$simple\\{file:name\\}", ""); 1469 pattern = pattern.replaceFirst("\\$\\{file:name.noext\\}", ""); 1470 pattern = pattern.replaceFirst("\\$simple\\{file:name.noext\\}", ""); 1471 1472 // must be able to resolve all placeholders supported 1473 if (StringHelper.hasStartToken(pattern, "simple")) { 1474 throw new ExpressionIllegalSyntaxException(fileName + ". Cannot resolve reminder: " + pattern); 1475 } 1476 1477 if (prefix) { 1478 return fileName.startsWith(pattern); 1479 } else { 1480 return fileName.endsWith(pattern); 1481 } 1482 } 1483 1484 @Override 1485 protected void doStart() throws Exception { 1486 // validate that the read lock options is valid for the process strategy 1487 if (!"none".equals(readLock) && !"off".equals(readLock)) { 1488 if (readLockTimeout > 0 && readLockTimeout <= readLockCheckInterval) { 1489 throw new IllegalArgumentException("The option readLockTimeout must be higher than readLockCheckInterval" 1490 + ", was readLockTimeout=" + readLockTimeout + ", readLockCheckInterval=" + readLockCheckInterval 1491 + ". A good practice is to let the readLockTimeout be at least 3 times higher than the readLockCheckInterval" 1492 + " to ensure that the read lock procedure has enough time to acquire the lock."); 1493 } 1494 } 1495 if ("idempotent".equals(readLock) && idempotentRepository == null) { 1496 throw new IllegalArgumentException("IdempotentRepository must be configured when using readLock=idempotent"); 1497 } 1498 1499 if (antInclude != null) { 1500 if (antFilter == null) { 1501 antFilter = new AntPathMatcherGenericFileFilter<>(); 1502 } 1503 antFilter.setIncludes(antInclude); 1504 } 1505 if (antExclude != null) { 1506 if (antFilter == null) { 1507 antFilter = new AntPathMatcherGenericFileFilter<>(); 1508 } 1509 antFilter.setExcludes(antExclude); 1510 } 1511 if (antFilter != null) { 1512 antFilter.setCaseSensitive(antFilterCaseSensitive); 1513 } 1514 1515 // idempotent repository may be used by others, so add it as a service so its stopped when CamelContext stops 1516 if (idempotentRepository != null) { 1517 getCamelContext().addService(idempotentRepository, true); 1518 } 1519 ServiceHelper.startServices(inProgressRepository); 1520 super.doStart(); 1521 } 1522 1523 @Override 1524 protected void doStop() throws Exception { 1525 super.doStop(); 1526 ServiceHelper.stopServices(inProgressRepository); 1527 } 1528}