View Javadoc

1   /*
2    * Copyright (C) The MetaClass Group. All rights reserved.
3    *
4    * This software is published under the terms of the Spice
5    * Software License version 1.1, a copy of which has been included
6    * with this distribution in the LICENSE.txt file.
7    */
8   package org.codehaus.metaclass.io;
9   
10  import java.io.File;
11  import java.io.FileOutputStream;
12  import java.io.OutputStream;
13  import org.codehaus.metaclass.model.ClassDescriptor;
14  
15  /***
16   * An abstract class that simplifies creation of MetaClassIO types.
17   *
18   * @author Peter Donald
19   * @version $Revision: 1.1 $ $Date: 2003/12/11 08:41:50 $
20   */
21  abstract class AbstractMetaClassIO
22      implements MetaClassIO
23  {
24      /***
25       * Implement in subclasses to actually serialize descriptor.
26       *
27       * @param output the output stream
28       * @param descriptor the descriptor
29       * @throws Exception if unable to serialize descriptor
30       */
31      public abstract void serializeClass( OutputStream output,
32                                           ClassDescriptor descriptor )
33          throws Exception;
34  
35      /***
36       * @see MetaClassIO#writeDescriptor(File, ClassDescriptor)
37       */
38      public void writeDescriptor( final File baseDir,
39                                   final ClassDescriptor descriptor )
40          throws Exception
41      {
42          final String filename = getResourceName( descriptor.getName() );
43          final File file = new File( baseDir, filename ).getCanonicalFile();
44          file.getParentFile().mkdirs();
45  
46          final OutputStream outputStream = new FileOutputStream( file );
47          try
48          {
49              serializeClass( outputStream, descriptor );
50              outputStream.close();
51          }
52          catch( final Exception e )
53          {
54              outputStream.close();
55              file.delete();
56              throw e;
57          }
58      }
59  }