001 /**************************************************************** 002 * Licensed to the Apache Software Foundation (ASF) under one * 003 * or more contributor license agreements. See the NOTICE file * 004 * distributed with this work for additional information * 005 * regarding copyright ownership. The ASF licenses this file * 006 * to you under the Apache License, Version 2.0 (the * 007 * "License"); you may not use this file except in compliance * 008 * with the License. You may obtain a copy of the License at * 009 * * 010 * http://www.apache.org/licenses/LICENSE-2.0 * 011 * * 012 * Unless required by applicable law or agreed to in writing, * 013 * software distributed under the License is distributed on an * 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * 015 * KIND, either express or implied. See the License for the * 016 * specific language governing permissions and limitations * 017 * under the License. * 018 ****************************************************************/ 019 020 package org.apache.james.mime4j.message; 021 022 /** 023 * Utility class for copying message bodies. 024 */ 025 public class BodyCopier { 026 027 private BodyCopier() { 028 } 029 030 /** 031 * Returns a copy of the given {@link Body} that can be used (and modified) 032 * independently of the original. The copy should be 033 * {@link Disposable#dispose() disposed of} when it is no longer needed. 034 * <p> 035 * The {@link Body#getParent() parent} of the returned copy is 036 * <code>null</code>, that is, the copy is detached from the parent 037 * entity of the original. 038 * 039 * @param body 040 * body to copy. 041 * @return a copy of the given body. 042 * @throws UnsupportedOperationException 043 * if <code>body</code> is an instance of {@link SingleBody} 044 * that does not support the {@link SingleBody#copy() copy()} 045 * operation (or contains such a <code>SingleBody</code>). 046 * @throws IllegalArgumentException 047 * if <code>body</code> is <code>null</code> or 048 * <code>body</code> is a <code>Body</code> that is neither 049 * a {@link Message}, {@link Multipart} or {@link SingleBody} 050 * (or contains such a <code>Body</code>). 051 */ 052 public static Body copy(Body body) { 053 if (body == null) 054 throw new IllegalArgumentException("Body is null"); 055 056 if (body instanceof Message) 057 return new Message((Message) body); 058 059 if (body instanceof Multipart) 060 return new Multipart((Multipart) body); 061 062 if (body instanceof SingleBody) 063 return ((SingleBody) body).copy(); 064 065 throw new IllegalArgumentException("Unsupported body class"); 066 } 067 068 }