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 package org.apache.camel.component.file; 015 016 import org.apache.camel.Exchange; 017 import org.apache.camel.Producer; 018 import org.apache.camel.impl.DefaultProducer; 019 import org.apache.commons.logging.Log; 020 import org.apache.commons.logging.LogFactory; 021 022 import java.io.File; 023 import java.io.RandomAccessFile; 024 import java.nio.ByteBuffer; 025 import java.nio.channels.FileChannel; 026 027 /** 028 * A {@link Producer} implementation for File 029 * 030 * @version $Revision: 523016 $ 031 */ 032 public class FileProducer extends DefaultProducer { 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(Exchange) 044 */ 045 public void process(Exchange exchange) { 046 process(endpoint.toExchangeType(exchange)); 047 } 048 049 public void process(FileExchange exchange){ 050 String fileName = exchange.getIn().getMessageId(); 051 ByteBuffer payload=exchange.getIn().getBody(ByteBuffer.class); 052 payload.flip(); 053 File file = null; 054 if(endpoint.getFile()!=null&&endpoint.getFile().isDirectory()){ 055 056 file=new File(endpoint.getFile(),fileName); 057 058 }else{ 059 file=new File(fileName); 060 } 061 buildDirectory(file); 062 try{ 063 FileChannel fc=new RandomAccessFile(file,"rw").getChannel(); 064 fc.position(fc.size()); 065 fc.write(payload); 066 fc.close(); 067 }catch(Throwable e){ 068 log.error("Failed to write to File: "+file,e); 069 } 070 } 071 072 private void buildDirectory(File file) { 073 String dirName = file.getAbsolutePath(); 074 int index = dirName.lastIndexOf(File.separatorChar); 075 if (index > 0) { 076 dirName = dirName.substring(0,index); 077 File dir = new File(dirName); 078 dir.mkdirs(); 079 } 080 } 081 }