001 /** 002 * 003 * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE 004 * file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file 005 * to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the 006 * License. You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 011 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 012 * specific language governing permissions and limitations under the License. 013 */ 014 015 package org.apache.camel.component.file; 016 017 import java.io.File; 018 import java.io.RandomAccessFile; 019 import java.nio.ByteBuffer; 020 import java.nio.channels.FileChannel; 021 import org.apache.camel.Producer; 022 import org.apache.camel.impl.DefaultProducer; 023 import org.apache.commons.logging.Log; 024 import org.apache.commons.logging.LogFactory; 025 026 /** 027 * A {@link Producer} implementation for File 028 * 029 * @version $Revision: 523016 $ 030 */ 031 public class FileProducer extends DefaultProducer<FileExchange>{ 032 033 private static final transient Log log=LogFactory.getLog(FileProducer.class); 034 private final FileEndpoint endpoint; 035 036 public FileProducer(FileEndpoint endpoint){ 037 super(endpoint); 038 this.endpoint=endpoint; 039 } 040 041 /** 042 * @param exchange 043 * @see org.apache.camel.Processor#process(java.lang.Object) 044 */ 045 public void process(FileExchange exchange){ 046 ByteBuffer payload=exchange.getIn().getBody(ByteBuffer.class); 047 payload.flip(); 048 File file=null; 049 if(endpoint.getFile()!=null&&endpoint.getFile().isDirectory()){ 050 file=new File(endpoint.getFile(),exchange.getFile().getName()); 051 }else{ 052 file=exchange.getFile(); 053 } 054 try{ 055 FileChannel fc=new RandomAccessFile(file,"rw").getChannel(); 056 fc.position(fc.size()); 057 fc.write(payload); 058 fc.close(); 059 }catch(Throwable e){ 060 log.error("Failed to write to File: "+file,e); 061 } 062 } 063 }