1 package org.alfresco.maven.plugin.amp.util;
2
3 import com.thoughtworks.xstream.XStream;
4
5 import java.io.File;
6 import java.io.FileReader;
7 import java.io.FileWriter;
8 import java.io.IOException;
9
10 /***
11 * Serializes {@link AmpStructure} back and forth.
12 *
13 * @author Stephane Nicoll
14 */
15 public class AmpStructureSerializer
16 {
17
18 private final XStream xStream;
19
20 /***
21 * Creates a new instance of the serializer.
22 */
23 public AmpStructureSerializer()
24 {
25 this.xStream = new XStream();
26
27
28 xStream.alias( "webapp-structure", AmpStructure.class );
29 xStream.alias( "path-set", PathSet.class );
30 }
31
32
33 /***
34 * Reads the {@link AmpStructure} from the specified file.
35 *
36 * @param file the file containing the webapp structure
37 * @return the webapp structure
38 * @throws IOException if an error occured while reading the structure
39 */
40 public AmpStructure fromXml( File file )
41 throws IOException
42 {
43 FileReader reader = null;
44
45 try
46 {
47 reader = new FileReader( file );
48 return (AmpStructure) xStream.fromXML( reader );
49 }
50 finally
51 {
52 if ( reader != null )
53 {
54 reader.close();
55 }
56 }
57 }
58
59 /***
60 * Saves the {@link AmpStructure} to the specified file.
61 *
62 * @param webappStructure the structure to save
63 * @param targetFile the file to use to save the structure
64 * @throws IOException if an error occured while saving the webapp structure
65 */
66 public void toXml( AmpStructure webappStructure, File targetFile )
67 throws IOException
68 {
69 FileWriter writer = null;
70 try
71 {
72 if ( !targetFile.getParentFile().exists() && !targetFile.getParentFile().mkdirs() )
73 {
74 throw new IOException(
75 "Could not create parent[" + targetFile.getParentFile().getAbsolutePath() + "]" );
76 }
77
78 if ( !targetFile.exists() && !targetFile.createNewFile() )
79 {
80 throw new IOException( "Could not create file[" + targetFile.getAbsolutePath() + "]" );
81 }
82 writer = new FileWriter( targetFile );
83 xStream.toXML( webappStructure, writer );
84 }
85 finally
86 {
87 if ( writer != null )
88 {
89 writer.close();
90 }
91 }
92 }
93 }